Introducción a la matriz multidimensional en PHP

Una matriz multidimensional no es nada extraordinario, sino una matriz dentro de otra matriz. Cada índice de la matriz contiene otra matriz en lugar de un solo elemento que nuevamente puede estar apuntando a otra matriz o a los elementos particulares. Se accede a estas sub-matrices dentro de la matriz utilizando las múltiples dimensiones que comienzan desde la matriz externa y se mueven hacia la matriz interna. Las dimensiones son básicamente los índices que se requieren para acceder o almacenar el valor en una posición particular en una matriz. Las matrices multidimensionales en php son muy utilizadas en aplicaciones en tiempo real, pero es bastante complicado tratarlas en comparación con las matrices unidimensionales debido a los múltiples corchetes y cierta complejidad para trabajar con ellas, ya sea accediendo o almacenando valores en un índice particular, se requiere el uso de bucles.

Sintaxis de matriz multidimensional en PHP

A continuación se muestra la sintaxis general de las matrices multidimensionales en PHP. Aunque las matrices multidimensionales en PHP pueden ser 2D, 3D, 4D, etc. Cuanto más matriz de dimensiones sea, más difícil será administrarlas y más se agregarán los corchetes delante del nombre de la matriz.

Sintaxis para matriz 2D:

array(
array(element1, element2, elements3, …),
array(element1, element2, elements3, …),
… so on
)

Sintaxis para la matriz 3D:

array(
array (
array(element1, element2, elements3, …),
array(element1, element2, elements3, …),
… so on
),
array (
array(element1, element2, elements3, …),
array(element1, element2, elements3, …),
… so on
),
… so on
)

¿Cómo declarar matrices multidimensionales en PHP?

PHP permite que sus matrices multidimensionales sean indexadas o asociativas. Las matrices asociativas son más interactivas en comparación con la indexada. PHP permite una manera muy simple de declarar una matriz multidimensional en PHP usando la palabra clave 'matriz'. Para declarar una matriz dentro de otra matriz, necesitamos agregar la palabra clave 'matriz' y luego los elementos de esa matriz.

1. Declaración de matriz 2D en PHP

Código:

<_?php
$employee_details = array();
$employee_details( ) = array(“Ram”, “Agra”, “Sr. Engineer”);
$employee_details( ) = array(“Raghav”, “Delhi”, “Jr. Engineer”);
?>

O

<_?php
$employee_details = array(
array(“Ram”, “Agra”, “Sr. Engineer”),
array(“Raghav”, “Delhi”, “Jr. Engineer”),
);
?>

El segundo método que se muestra arriba se usa comúnmente, ya que es bastante fácil de entender.

2. Declaración de matriz 3D en PHP

Código:

<_?php
/* Simplest way to declare a 3D array in Php in an indexed manner */
$item_details = array(
array(
array (“item1”, “abc”, 100)),
array (“item2”, “bcd”, 200)),
array (“item3”, “def”, 300)),
),
array(
array (“item4”, “abc4”, 100)),
array (“item5, “bcd5”, 200)),
array (“item6”, “def6”, 300)),
),
);
?>

La declaración anterior está puramente indexada en una de las matrices 3D, ya que no se utilizan pares clave-valor para la asociación.

¿Cómo inicializar una matriz multidimensional en PHP?

Inicializar una matriz multidimensional significa asignar los valores o elementos en la posición particular o los índices de una matriz. Inicializar una matriz multidimensional en PHP es bastante fácil como declarar. Lo único a tener en cuenta es el uso de llaves mientras se inicializan las submatrices. Al inicializar los valores en una matriz multidimensional, la matriz principal puede ser indexada o asociativa, en el ejemplo que se muestra a continuación, la matriz principal es la asociativa que tiene las claves como Levis, Lee, Denizen, Etc.,

1. Inicializando matriz 2D en PHP

Código:

<_?php
/* It is a multidimensional 2D array of clothes in which the main array holds another arrays of having 2 elements like cloth type and quantity */
/* It is associative kind of array having the data in the form of key => value pairs. So the data at the inner subarray is represented as associated by the key element.*/
$clothes = array(
“Levis” => array(
“Cloth_type” => “jeans”,
“Quantity” => 20
),
“Pepe” => array(
“Cloth_type” => “jeans”,
“Quantity” => 100
),
“Lee” => array(
“Cloth_type” => “tshirts”,
“Quantity” => 50
),
“Denizen” => array(
“Cloth_type” => “tops”,
“Quantity” => 80
)
);
?>

2. Inicializando Matriz 3D en PHP

La inicialización de las matrices 3D es la misma que las matrices 2D, la única diferencia entre las dos son las dimensiones. La matriz 3D requiere 1 índice más para inicializar que una matriz 2D. La cantidad de dimensiones de la matriz aumenta, la cantidad de índices para inicializarla también aumenta. En el siguiente ejemplo, la matriz principal es una matriz indexada simple que tiene sub-matrices en sí misma. También podemos hacer que la matriz principal en el ejemplo a continuación sea tan asociativa como lo hemos hecho en una matriz 2D con la clave como el nombre de la marca, lo que facilita que el cliente entienda mientras accede y almacena.

Código:

<_?php
/* In this there is a 3D array of clothes in which each element have an array of cloth type, brand and quantity of that particular brand. Each brand has different quantity and cloth type.*/
$clothes = array(
array(
array(
“Brand” => “Levis”,
“Cloth_type” => “jeans”,
“Quantity” => 20
),
array(
“Brand” => “Levis”,
“Cloth_type” => “Tops”,
“Quantity” => 100
)
),
array(
array(
“Brand” => “Lee”,
“Cloth_type” => “jeans”,
“Quantity” => 50
),
array(
“Brand” => “Lee”,
“Cloth_type” => “tops”,
“Quantity” => 80
)
),
);
?>

Acceso a matrices multidimensionales en PHP

El acceso a matrices multidimensionales en PHP es muy simple y se realiza mediante el uso de for o for each loop, que son los bucles comúnmente utilizados en PHP. Para las matrices indexadas, el acceso a los elementos de la matriz se puede hacer normalmente utilizando el número de fila y columna similar a otros lenguajes como C, Java, Etc. (arr (row_Num) (column_Num))

En el caso de las matrices asociativas, el acceso a los elementos de una matriz multidimensional se realiza utilizando la clave y los pares de valores (clave => Valor). Aunque se accede a los elementos a través del simple para o para cada bucle. Consulte el siguiente ejemplo para obtener una comprensión clara del acceso a elementos en matrices multidimensionales.

Tipos de matriz multidimensional en PHP

No hay un estado particular hasta el cual las matrices multidimensionales puedan existir en un PHP. Depende de la situación particular y el escenario. Las dimensiones de una matriz varían en consecuencia. Normalmente, los programadores usan matrices 2D y 3D porque, después de las matrices 3D, es un poco difícil administrarlas.

Como hemos entendido la declaración, la inicialización y el acceso a las matrices multidimensionales en PHP, es hora de una breve explicación rápida con ejemplos.

1. Matriz 2D en PHP

Las matrices 2D son básicamente matrices dentro de otra matriz. Considere un escenario en el que un usuario tiene 10 libros y cada libro tiene un nombre, costo y tipo diferente. En este caso, el programador puede crear una matriz de números de libros y cada elemento de la matriz principal contiene la matriz que contiene detalles del libro como nombre, costo y tipo.

Código:



/* Multidimensional 2D array for 4 books and each book having a different array containing book name, cost and type. */
$books = array(
array("Fiction ", "Action and Adventure ", 800),
array("Fiction ", "Anthology ", 1000),
array("Non- Fiction ", "Biography ", 600),
array("Non- Fiction ", "Cook Book ", 900)
);
/* Accessing of a 2D array with the row_number and column_number */
for ($row_num = 0; $row_num < 4; $row_num++) (
echo "
<_?php


/* Multidimensional 2D array for 4 books and each book having a different array containing book name, cost and type. */
$books = array(
array("Fiction ", "Action and Adventure ", 800),
array("Fiction ", "Anthology ", 1000),
array("Non- Fiction ", "Biography ", 600),
array("Non- Fiction ", "Cook Book ", 900)
);
/* Accessing of a 2D array with the row_number and column_number */
for ($row_num = 0; $row_num < 4; $row_num++) (
echo "

El número de libro es $ row_num

";
para ($ col_num = 0; $ col_num <3; $ col_num ++) (
// Accediendo a un elemento particular en una matriz 2D
echo $ libros ($ row_num) ($ col_num);
)
eco "
";
)
?>

Salida:

2. Matriz 3D en PHP

Las matrices 3D son una extensión de las matrices 2D. Las matrices 3D contienen una dimensión más y brindan la posibilidad de agregar información más detallada. Considere un escenario de matriz de empleados, en el que los empleados tienen nombre, empresa y año y cada empleado tiene un perfil de empresa con los atributos id, habilidades y perfil. Cada empleado tiene datos personales también con los detalles de la ciudad, el estado y el país. En orden, para almacenar, se requeriría la matriz 3D de datos anteriores.

Código:



$Employee = array(array(array("name", "company", "year"),
array("id", "skills", "profile"),
array("city", "state", "country")
),
/* array to store the name, company and year of employee*/
array(array("jiya", "Infosys", 2016),
array("ram", "ola", 2017)
),
/* array to store the id, skills and profile of employees */
array(array("E101", "PHP", "developer"),
array("E103", "mysql", "DBA")
),
/* array to store the city, state and country of employees */
array(array("Bangalore", "Karnataka", "India"),
array("San Francisco", "California", "USA")
)
);
?>
echo " ";
for ( $outermost = 0; $outermost < 3; $outermost++ )
(
echo " The outermost number $outermost";
echo " ";
for ( $row_num = 0; $row_num < 2; $row_num++ )
(
echo " Now displaying the row number $row_num";
echo " ";
for ( $col_num = 0; $col_num < 3; $col_num++ )
(
// accessing the array elements in a 3D array
echo " ".$Employee($outermost)($row_num)($col_num)." ";
)
echo " ";
echo " ";
)
echo " ";
echo " ";
)
echo " ";
?>
<_?php


$Employee = array(array(array("name", "company", "year"),
array("id", "skills", "profile"),
array("city", "state", "country")
),
/* array to store the name, company and year of employee*/
array(array("jiya", "Infosys", 2016),
array("ram", "ola", 2017)
),
/* array to store the id, skills and profile of employees */
array(array("E101", "PHP", "developer"),
array("E103", "mysql", "DBA")
),
/* array to store the city, state and country of employees */
array(array("Bangalore", "Karnataka", "India"),
array("San Francisco", "California", "USA")
)
);
?>
echo " ";
for ( $outermost = 0; $outermost < 3; $outermost++ )
(
echo " The outermost number $outermost";
echo " ";
for ( $row_num = 0; $row_num < 2; $row_num++ )
(
echo " Now displaying the row number $row_num";
echo " ";
for ( $col_num = 0; $col_num < 3; $col_num++ )
(
// accessing the array elements in a 3D array
echo " ".$Employee($outermost)($row_num)($col_num)." ";
)
echo " ";
echo " ";
)
echo " ";
echo " ";
)
echo " ";
?>
<_?php


$Employee = array(array(array("name", "company", "year"),
array("id", "skills", "profile"),
array("city", "state", "country")
),
/* array to store the name, company and year of employee*/
array(array("jiya", "Infosys", 2016),
array("ram", "ola", 2017)
),
/* array to store the id, skills and profile of employees */
array(array("E101", "PHP", "developer"),
array("E103", "mysql", "DBA")
),
/* array to store the city, state and country of employees */
array(array("Bangalore", "Karnataka", "India"),
array("San Francisco", "California", "USA")
)
);
?>
echo " ";
for ( $outermost = 0; $outermost < 3; $outermost++ )
(
echo " The outermost number $outermost";
echo " ";
for ( $row_num = 0; $row_num < 2; $row_num++ )
(
echo " Now displaying the row number $row_num";
echo " ";
for ( $col_num = 0; $col_num < 3; $col_num++ )
(
// accessing the array elements in a 3D array
echo " ".$Employee($outermost)($row_num)($col_num)." ";
)
echo " ";
echo " ";
)
echo " ";
echo " ";
)
echo " ";
?>



    $Employee = array(array(array("name", "company", "year"),
    array("id", "skills", "profile"),
    array("city", "state", "country")
    ),
    /* array to store the name, company and year of employee*/
    array(array("jiya", "Infosys", 2016),
    array("ram", "ola", 2017)
    ),
    /* array to store the id, skills and profile of employees */
    array(array("E101", "PHP", "developer"),
    array("E103", "mysql", "DBA")
    ),
    /* array to store the city, state and country of employees */
    array(array("Bangalore", "Karnataka", "India"),
    array("San Francisco", "California", "USA")
    )
    );
    ?>
    echo " ";
    for ( $outermost = 0; $outermost < 3; $outermost++ )
    (
    echo " The outermost number $outermost";
    echo " ";
    for ( $row_num = 0; $row_num < 2; $row_num++ )
    (
    echo " Now displaying the row number $row_num";
    echo " ";
    for ( $col_num = 0; $col_num < 3; $col_num++ )
    (
    // accessing the array elements in a 3D array
    echo " ".$Employee($outermost)($row_num)($col_num)." ";
    )
    echo " ";
    echo " ";
    )
    echo " ";
    echo " ";
    )
    echo " ";
    ?>


  • $Employee = array(array(array("name", "company", "year"),
    array("id", "skills", "profile"),
    array("city", "state", "country")
    ),
    /* array to store the name, company and year of employee*/
    array(array("jiya", "Infosys", 2016),
    array("ram", "ola", 2017)
    ),
    /* array to store the id, skills and profile of employees */
    array(array("E101", "PHP", "developer"),
    array("E103", "mysql", "DBA")
    ),
    /* array to store the city, state and country of employees */
    array(array("Bangalore", "Karnataka", "India"),
    array("San Francisco", "California", "USA")
    )
    );
    ?>
    echo " ";
    for ( $outermost = 0; $outermost < 3; $outermost++ )
    (
    echo " The outermost number $outermost";
    echo " ";
    for ( $row_num = 0; $row_num < 2; $row_num++ )
    (
    echo " Now displaying the row number $row_num";
    echo " ";
    for ( $col_num = 0; $col_num < 3; $col_num++ )
    (
    // accessing the array elements in a 3D array
    echo " ".$Employee($outermost)($row_num)($col_num)." ";
    )
    echo " ";
    echo " ";
    )
    echo " ";
    echo " ";
    )
    echo " ";
    ?>


      $Employee = array(array(array("name", "company", "year"),
      array("id", "skills", "profile"),
      array("city", "state", "country")
      ),
      /* array to store the name, company and year of employee*/
      array(array("jiya", "Infosys", 2016),
      array("ram", "ola", 2017)
      ),
      /* array to store the id, skills and profile of employees */
      array(array("E101", "PHP", "developer"),
      array("E103", "mysql", "DBA")
      ),
      /* array to store the city, state and country of employees */
      array(array("Bangalore", "Karnataka", "India"),
      array("San Francisco", "California", "USA")
      )
      );
      ?>
      echo " ";
      for ( $outermost = 0; $outermost < 3; $outermost++ )
      (
      echo " The outermost number $outermost";
      echo " ";
      for ( $row_num = 0; $row_num < 2; $row_num++ )
      (
      echo " Now displaying the row number $row_num";
      echo " ";
      for ( $col_num = 0; $col_num < 3; $col_num++ )
      (
      // accessing the array elements in a 3D array
      echo " ".$Employee($outermost)($row_num)($col_num)." ";
      )
      echo " ";
      echo " ";
      )
      echo " ";
      echo " ";
      )
      echo " ";
      ?>


    • $Employee = array(array(array("name", "company", "year"),
      array("id", "skills", "profile"),
      array("city", "state", "country")
      ),
      /* array to store the name, company and year of employee*/
      array(array("jiya", "Infosys", 2016),
      array("ram", "ola", 2017)
      ),
      /* array to store the id, skills and profile of employees */
      array(array("E101", "PHP", "developer"),
      array("E103", "mysql", "DBA")
      ),
      /* array to store the city, state and country of employees */
      array(array("Bangalore", "Karnataka", "India"),
      array("San Francisco", "California", "USA")
      )
      );
      ?>
      echo " ";
      for ( $outermost = 0; $outermost < 3; $outermost++ )
      (
      echo " The outermost number $outermost";
      echo " ";
      for ( $row_num = 0; $row_num < 2; $row_num++ )
      (
      echo " Now displaying the row number $row_num";
      echo " ";
      for ( $col_num = 0; $col_num < 3; $col_num++ )
      (
      // accessing the array elements in a 3D array
      echo " ".$Employee($outermost)($row_num)($col_num)." ";
      )
      echo " ";
      echo " ";
      )
      echo " ";
      echo " ";
      )
      echo " ";
      ?>


        $Employee = array(array(array("name", "company", "year"),
        array("id", "skills", "profile"),
        array("city", "state", "country")
        ),
        /* array to store the name, company and year of employee*/
        array(array("jiya", "Infosys", 2016),
        array("ram", "ola", 2017)
        ),
        /* array to store the id, skills and profile of employees */
        array(array("E101", "PHP", "developer"),
        array("E103", "mysql", "DBA")
        ),
        /* array to store the city, state and country of employees */
        array(array("Bangalore", "Karnataka", "India"),
        array("San Francisco", "California", "USA")
        )
        );
        ?>
        echo " ";
        for ( $outermost = 0; $outermost < 3; $outermost++ )
        (
        echo " The outermost number $outermost";
        echo " ";
        for ( $row_num = 0; $row_num < 2; $row_num++ )
        (
        echo " Now displaying the row number $row_num";
        echo " ";
        for ( $col_num = 0; $col_num < 3; $col_num++ )
        (
        // accessing the array elements in a 3D array
        echo " ".$Employee($outermost)($row_num)($col_num)." ";
        )
        echo " ";
        echo " ";
        )
        echo " ";
        echo " ";
        )
        echo " ";
        ?>


      • $Employee = array(array(array("name", "company", "year"),
        array("id", "skills", "profile"),
        array("city", "state", "country")
        ),
        /* array to store the name, company and year of employee*/
        array(array("jiya", "Infosys", 2016),
        array("ram", "ola", 2017)
        ),
        /* array to store the id, skills and profile of employees */
        array(array("E101", "PHP", "developer"),
        array("E103", "mysql", "DBA")
        ),
        /* array to store the city, state and country of employees */
        array(array("Bangalore", "Karnataka", "India"),
        array("San Francisco", "California", "USA")
        )
        );
        ?>
        echo " ";
        for ( $outermost = 0; $outermost < 3; $outermost++ )
        (
        echo " The outermost number $outermost";
        echo " ";
        for ( $row_num = 0; $row_num < 2; $row_num++ )
        (
        echo " Now displaying the row number $row_num";
        echo " ";
        for ( $col_num = 0; $col_num < 3; $col_num++ )
        (
        // accessing the array elements in a 3D array
        echo " ".$Employee($outermost)($row_num)($col_num)." ";
        )
        echo " ";
        echo " ";
        )
        echo " ";
        echo " ";
        )
        echo " ";
        ?>


      • $Employee = array(array(array("name", "company", "year"),
        array("id", "skills", "profile"),
        array("city", "state", "country")
        ),
        /* array to store the name, company and year of employee*/
        array(array("jiya", "Infosys", 2016),
        array("ram", "ola", 2017)
        ),
        /* array to store the id, skills and profile of employees */
        array(array("E101", "PHP", "developer"),
        array("E103", "mysql", "DBA")
        ),
        /* array to store the city, state and country of employees */
        array(array("Bangalore", "Karnataka", "India"),
        array("San Francisco", "California", "USA")
        )
        );
        ?>
        echo " ";
        for ( $outermost = 0; $outermost < 3; $outermost++ )
        (
        echo " The outermost number $outermost";
        echo " ";
        for ( $row_num = 0; $row_num < 2; $row_num++ )
        (
        echo " Now displaying the row number $row_num";
        echo " ";
        for ( $col_num = 0; $col_num < 3; $col_num++ )
        (
        // accessing the array elements in a 3D array
        echo " ".$Employee($outermost)($row_num)($col_num)." ";
        )
        echo " ";
        echo " ";
        )
        echo " ";
        echo " ";
        )
        echo " ";
        ?>


      $Employee = array(array(array("name", "company", "year"),
      array("id", "skills", "profile"),
      array("city", "state", "country")
      ),
      /* array to store the name, company and year of employee*/
      array(array("jiya", "Infosys", 2016),
      array("ram", "ola", 2017)
      ),
      /* array to store the id, skills and profile of employees */
      array(array("E101", "PHP", "developer"),
      array("E103", "mysql", "DBA")
      ),
      /* array to store the city, state and country of employees */
      array(array("Bangalore", "Karnataka", "India"),
      array("San Francisco", "California", "USA")
      )
      );
      ?>
      echo " ";
      for ( $outermost = 0; $outermost < 3; $outermost++ )
      (
      echo " The outermost number $outermost";
      echo " ";
      for ( $row_num = 0; $row_num < 2; $row_num++ )
      (
      echo " Now displaying the row number $row_num";
      echo " ";
      for ( $col_num = 0; $col_num < 3; $col_num++ )
      (
      // accessing the array elements in a 3D array
      echo " ".$Employee($outermost)($row_num)($col_num)." ";
      )
      echo " ";
      echo " ";
      )
      echo " ";
      echo " ";
      )
      echo " ";
      ?>


    • $Employee = array(array(array("name", "company", "year"),
      array("id", "skills", "profile"),
      array("city", "state", "country")
      ),
      /* array to store the name, company and year of employee*/
      array(array("jiya", "Infosys", 2016),
      array("ram", "ola", 2017)
      ),
      /* array to store the id, skills and profile of employees */
      array(array("E101", "PHP", "developer"),
      array("E103", "mysql", "DBA")
      ),
      /* array to store the city, state and country of employees */
      array(array("Bangalore", "Karnataka", "India"),
      array("San Francisco", "California", "USA")
      )
      );
      ?>
      echo " ";
      for ( $outermost = 0; $outermost < 3; $outermost++ )
      (
      echo " The outermost number $outermost";
      echo " ";
      for ( $row_num = 0; $row_num < 2; $row_num++ )
      (
      echo " Now displaying the row number $row_num";
      echo " ";
      for ( $col_num = 0; $col_num < 3; $col_num++ )
      (
      // accessing the array elements in a 3D array
      echo " ".$Employee($outermost)($row_num)($col_num)." ";
      )
      echo " ";
      echo " ";
      )
      echo " ";
      echo " ";
      )
      echo " ";
      ?>


    $Employee = array(array(array("name", "company", "year"),
    array("id", "skills", "profile"),
    array("city", "state", "country")
    ),
    /* array to store the name, company and year of employee*/
    array(array("jiya", "Infosys", 2016),
    array("ram", "ola", 2017)
    ),
    /* array to store the id, skills and profile of employees */
    array(array("E101", "PHP", "developer"),
    array("E103", "mysql", "DBA")
    ),
    /* array to store the city, state and country of employees */
    array(array("Bangalore", "Karnataka", "India"),
    array("San Francisco", "California", "USA")
    )
    );
    ?>
    echo " ";
    for ( $outermost = 0; $outermost < 3; $outermost++ )
    (
    echo " The outermost number $outermost";
    echo " ";
    for ( $row_num = 0; $row_num < 2; $row_num++ )
    (
    echo " Now displaying the row number $row_num";
    echo " ";
    for ( $col_num = 0; $col_num < 3; $col_num++ )
    (
    // accessing the array elements in a 3D array
    echo " ".$Employee($outermost)($row_num)($col_num)." ";
    )
    echo " ";
    echo " ";
    )
    echo " ";
    echo " ";
    )
    echo " ";
    ?>


  • $Employee = array(array(array("name", "company", "year"),
    array("id", "skills", "profile"),
    array("city", "state", "country")
    ),
    /* array to store the name, company and year of employee*/
    array(array("jiya", "Infosys", 2016),
    array("ram", "ola", 2017)
    ),
    /* array to store the id, skills and profile of employees */
    array(array("E101", "PHP", "developer"),
    array("E103", "mysql", "DBA")
    ),
    /* array to store the city, state and country of employees */
    array(array("Bangalore", "Karnataka", "India"),
    array("San Francisco", "California", "USA")
    )
    );
    ?>
    echo " ";
    for ( $outermost = 0; $outermost < 3; $outermost++ )
    (
    echo " The outermost number $outermost";
    echo " ";
    for ( $row_num = 0; $row_num < 2; $row_num++ )
    (
    echo " Now displaying the row number $row_num";
    echo " ";
    for ( $col_num = 0; $col_num < 3; $col_num++ )
    (
    // accessing the array elements in a 3D array
    echo " ".$Employee($outermost)($row_num)($col_num)." ";
    )
    echo " ";
    echo " ";
    )
    echo " ";
    echo " ";
    )
    echo " ";
    ?>


$Employee = array(array(array("name", "company", "year"),
array("id", "skills", "profile"),
array("city", "state", "country")
),
/* array to store the name, company and year of employee*/
array(array("jiya", "Infosys", 2016),
array("ram", "ola", 2017)
),
/* array to store the id, skills and profile of employees */
array(array("E101", "PHP", "developer"),
array("E103", "mysql", "DBA")
),
/* array to store the city, state and country of employees */
array(array("Bangalore", "Karnataka", "India"),
array("San Francisco", "California", "USA")
)
);
?>
echo " ";
for ( $outermost = 0; $outermost < 3; $outermost++ )
(
echo " The outermost number $outermost";
echo " ";
for ( $row_num = 0; $row_num < 2; $row_num++ )
(
echo " Now displaying the row number $row_num";
echo " ";
for ( $col_num = 0; $col_num < 3; $col_num++ )
(
// accessing the array elements in a 3D array
echo " ".$Employee($outermost)($row_num)($col_num)." ";
)
echo " ";
echo " ";
)
echo " ";
echo " ";
)
echo " ";
?>

Salida:

El ejemplo anterior muestra claramente los detalles del empleado junto con sus habilidades de una manera muy fácil de usar. Permite detallar a todos y cada uno de los empleados en una sofisticada matriz en 3D. Estamos tratando con matrices 3D, para acceder a eso, primero debemos llegar a la matriz principal y luego al índice que nuevamente contiene la submatriz y luego a los elementos de su submatriz. De esta manera, el acceso a los elementos funciona en el caso de matrices multidimensionales que comienzan desde la matriz más externa a la más interna. Del mismo modo, en la vida real, hay sub-matrices o elementos detallados en los que se utilizan matrices multidimensionales.

Conclusión

La explicación anterior muestra claramente cómo se usan las matrices multidimensionales en php junto con su sintaxis e inicialización básicas. Las matrices multidimensionales juegan un papel importante cuando se trata de trabajar en problemas de la vida real, ya que permiten al usuario almacenar los datos de forma detallada. Además, como se muestra arriba, php permite almacenar los datos multidimensionales ya sea en forma indexada o asociativa de acuerdo con los requisitos, lo que hace que sea más fácil acceder y almacenar los datos.

Artículos recomendados

Esta es una guía para la matriz multidimensional en PHP. Aquí discutimos la declaración, inicialización de una matriz multidimensional en php con sus tipos. También puede consultar los siguientes artículos para obtener más información:

  1. PHP Magic Constants (Trabajo y ejemplos)
  2. Las 13 principales características clave de Laravel
  3. Programación de sockets en PHP
  4. Tipos de sobrecarga en PHP
  5. Bucles en VBScript con ejemplos
  6. Programación de sockets en Python