23 of 110 menu

Matriz multidimensional en PHP

Una matriz multidimensional es una matriz cuyos elementos también son matrices.

He aquí un ejemplo de matriz bidimensional:

<?php $arr = [[1, 2, 3], [4, 5⁆, 6], [7, 8, 9]]; ?>

He aquí un ejemplo de matriz tridimensional:

<?php $arr = [[[1, 2], [3, 4]], [5, 6]]; ?>

Y así sucesivamente - las matrices pueden tener cualquier nivel de anidamiento.

Cómo mostrar un elemento de una matriz multidimensional

Supongamos que tenemos la siguiente matriz:

<?php $arr = [ 'boys' => ['John', 'Nick', 'Mike'], 'girls' => ['Mary', 'Natasha', 'Helen'], ]; echo $arr['boys'][0]; ?>

Vamos a mostrar, usando nuestra matriz, por ejemplo, 'Nick':

<?php $arr = [ 'boys' => ['John', 'Nick', 'Mike'], 'girls' => ['Mary', 'Natasha', 'Helen'], ]; echo $arr['boys'][1]; // mostrará 'Nick' ?>

Y ahora mostremos 'Helen':

<?php $arr = [ 'boys' => ['John', 'Nick', 'Mike'], 'girls' => ['Mary', 'Natasha', 'Helen'], ]; echo $arr['girls'][2]; // mostrará 'Helen' ?>

Ejemplo de recorrido de una matriz

Supongamos que tenemos una matriz:

<?php $arr = [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]]; ?>

Mostremos todos sus elementos en pantalla. Para ello, necesitamos ejecutar dos bucles anidados uno dentro del otro:

<?php $arr = [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]]; foreach ($arr as $elem) { foreach ($elem as $subElem) { echo $subElem; } } ?>

Ver también

Español
БеларускаяEnglishРусский
Usamos cookies para el funcionamiento del sitio, análisis y personalización. El procesamiento de datos se realiza de acuerdo con la Política de privacidad.
aceptar todas configurar rechazar