【问题标题】:how to parse this kind of json array如何解析这种json数组
【发布时间】:2016-12-06 14:43:07
【问题描述】:

我有一个类似自爆的 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”,我的 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/>";
}

输出:

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

【问题讨论】:

标签: javascript php arrays json web


【解决方案1】:

尝试使用foreach

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

【讨论】:

    【解决方案2】:

    如果你想使用你的代码来回显,在从数组中删除一个值后使用$newarray=array_values($oldarray)重新索引数组。

    【讨论】:

      【解决方案3】:

      这是因为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/>";
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        • 2017-04-12
        • 2018-06-17
        • 2018-03-01
        • 2021-08-29
        相关资源
        最近更新 更多