如何解析这种json数组

时间:2016-08-01 13:29:07

标签: javascript php arrays json web

我有一个像吹响的json数组:

    {
    "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"
    }
}

我删除了一个元素' Piranha the Fish'使用(UNSET)我的json代码改为打击:

{
    "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"
    }
}

当我删除元素时,元素的计数器变为0,1,3 所以现在我无法在我的json元素中拥有完全访问权限

我希望使用此代码回显值:

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

3 个答案:

答案 0 :(得分:2)

尝试使用foreach

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

答案 1 :(得分:0)

如果要使用代码进行回显,则在从数组中删除值后,使用$newarray=array_values($oldarray)重新索引数组。

答案 2 :(得分:0)

这是因为unset()从数组中删除了值和键/索引,并保持原样,即它不重新排列键/索引。

如果您想重新排列密钥,请使用array_slice()代替array_slice。你会得到你想要的东西。你将能够做到

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/>";
}