I have this multidimensional array with the name $mensajes
:
[0] => Array (
[id] => 140
[titulo] => titulo mensaje 1
[contenido] => contenido mensaje 1
[createAt] => 2019-04-25 20:27:59
[creador] => 1
[url_img] => 5cc1fc2f3462c0.37633589.png
[etiquetas] => Array (
[ids] => Array (
[0] => 90
[1] => 89
)
[nombres] => Array (
[0] => etiqueta_mensaje_uno
[1] => comun
)
)
)
[1] => Array (
[id] => 141
[titulo] => titulo mensaje 2
[contenido] => contenido mensaje 2
[createAt] => 2019-04-25 20:29:15
[creador] => 1
[url_img] => 5cc1fc7ba0c713.37620569.png
[etiquetas] => Array (
[ids] => Array (
[0] => 91
[1] => 89
)
[nombres] => Array (
[0] => etiqueta_mensaje_dos
[1] => comun
)
)
)
First out of curiosity I did a var_dump()
but I don't get all the data from it, the arrays
children are shown to me with a few simple points ...
, and that and nothing is the same.
array (size=2)
0 =>
array (size=7)
'id' => string '140' (length=3)
'titulo' => string 'titulo mensaje 1' (length=16)
'contenido' => string 'contenido mensaje 1' (length=19)
'createAt' => string '2019-04-25 20:27:59' (length=19)
'creador' => string '1' (length=1)
'url_img' => string '5cc1fc2f3462c0.37633589.png' (length=27)
'etiquetas' =>
array (size=2)
'ids' =>
array (size=2)
...
'nombres' =>
array (size=2)
...
1 =>
array (size=7)
'id' => string '141' (length=3)
'titulo' => string 'titulo mensaje 2' (length=16)
'contenido' => string 'contenido mensaje 2' (length=19)
'createAt' => string '2019-04-25 20:29:15' (length=19)
'creador' => string '1' (length=1)
'url_img' => string '5cc1fc7ba0c713.37620569.png' (length=27)
'etiquetas' =>
array (size=2)
'ids' =>
array (size=2)
...
'nombres' =>
array (size=2)
...
I tried to go through them with one foreach()
that would be logical, but apparently it has conflicts when reading the arrays
children:
foreach ($mensajes as $key ) {
echo "<p>" . $key['id'] . "</p>";
echo "<p>" . $key['titulo'] . "</p>";
echo "<p>" . $key['contenido'] . "</p>";
echo "<p>" . $key['createAt'] . "</p>";
echo "<p>" . $key['creador'] . "</p>";
echo "<p>" . $key['url_img'] . "</p>";
foreach ($key['etiquetas'] as $key2 ) {
echo "<p>" . $key2['ids'] . "</p>";
echo "<p>" . $key2['nombres'] . "</p>";
}
echo "----------------<br>";
}
What is the optimal way to go through me array
that is in an associative way of course, without numbers in the indexes but its key
Since you have the array organized, you cannot access the arrays inside
etiquetas
using the nested for.The problem is that the arrays are in the keys
ids
andnombres
so you would have to access them directly from$key
and start looping through them with a for, or use conditionals or something.The simplest way might be by reaching the arrays directly and then outputting the values as
implode
.Let's look at an example:
Departure: