how can I extract the colors of a json with foreach - while?

0

How can I extract the colors of this json?

[{
"item1": "si",
"item2": "no",
"item3":
[ 
{
"color": "azul",
"tipo": "circulo"
},
{
"color": "rojo",
"tipo": "triangulo" 
},
{
"color": "verde",
"tipo": "cuadrado"
}
]
}
]

This is what I do and if I extract item1 and item2, but in item3 it shows me the Array pabra.

$array = json_decode($data);  

foreach($array as $colors=>$color){
echo "$colors:<br>";
while (list($clave,$valor)=each($color)){
echo "$clave=$valor<br>";
}
}
    
asked by Rafel C.F 25.02.2017 в 16:37
source

2 answers

1

First, what you do to decode:

$array = json_decode($data);  

You are $ data parsing as an object. By the name of the variable I interpret that you want an array, so

$array = json_decode($data,true);  

Done this, if you know that your item3 has the form item3 = >[{color,tipo},{color,tipo},{color,tipo}] and you want to print its content.

foreach($array['item3'] as $pares){

    echo "Colores:<br>";

    foreach($pares as $llave=>$valor) {
        echo "$llave = $valor <br>";
    }
}

I should give you:

Colores:
  color=azul,
  tipo=circulo
Colores:
  color= rojo,
  tipo=triangulo
Colores:
  color=verde,
  tipo=cuadrado

This may not be exactly what you need to do. If you want an algorithm to go through a generic array, checking if any of its keys has an array value, it is more or less the same with a little more added logic.

    
answered by 25.02.2017 / 17:59
source
1

try this

foreach($data as $colors => $color){
    echo "$colors:<br>";
    while (list($clave,$valor)=each($color)){
        if (is_array($valor)) {
            $string = '';
            foreach ($valor as $v) {
                $string .= ' '.$v['color'];
            }
            $valor = $string;
        }
        echo "$clave = $valor<br>";
    }
}
    
answered by 25.02.2017 в 17:11