Mohammadali mirahamed Mohammadali mirahamed - 4 months ago 12
JSON Question

how to parse this kind of json array

I have a json array like blew :

{
"0": {
"kind": "mammal",
"name": "Pussy the Cat",
"weight": "12kg",
"age": "5"
},
"1": {
"kind": "mammal",
"name": "Roxy the Dog",
"weight": "25kg",
"age": "8"
},
"2": {
"kind": "fish",
"name": "Piranha the Fish",
"weight": "1kg",
"age": "1"
},
"3": {
"kind": "bird",
"name": "Einstein the Parrot",
"weight": "0.5kg",
"age": "4"
}
}


i removed an element 'Piranha the Fish' With (UNSET) My json code changed to blow:

{
"0": {
"kind": "mammal",
"name": "Pussy the Cat",
"weight": "12kg",
"age": "5"
},
"1": {
"kind": "mammal",
"name": "Roxy the Dog",
"weight": "25kg",
"age": "8"
},
"3": {
"kind": "bird",
"name": "Einstein the Parrot",
"weight": "0.5kg",
"age": "4"
}
}


when I remove element the counter of the element change to 0,1,3
so now i can't to have full access in my json elements

I want echo value with this code :

for ($i = 0; $i < $JsonCount - 1; $i++) {
echo "Name :";
echo $json_cod[$i]['name'];
echo "<br/>";
echo "Age :";
echo $json_cod[$i]['age'];
echo "<br/>";
}


out put :

Name :Pussy the Cat
Age :5
Name :Roxy the Dog
Age :8

Answer

Try using foreach.

foreach ($json_cod as $item) {
  echo "Name :";echo $item['name'];echo "<br/>";
  echo "Age :";echo $item['age'];echo "<br/>";
}