php中的json_encode数组 - 获取键和值

时间:2014-04-04 18:43:38

标签: javascript php

我有一个来自javascript / jquery的POST请求的数组。在php中,数组内容如下:

[{"name":"Ta","def":"somestring"},{"name":"WSCall","def":"somestring"},{"name":"manual","def":"somestring"}]

如何迭代此数组以获取键和值?

当我这样做时:json_decode($_POST['shape_defs'])

如何迭代此数组。做foreach说:

  

为foreach()提供的参数无效

3 个答案:

答案 0 :(得分:2)

虽然(当前)其他两个答案确实得到了正常工作的代码,但是他们无法解决你为什么会遇到错误。

$data = json_decode($j);
var_dump($data);

这将生成一个对象,其中键作为属性。除非实现foreach,否则对象无效传递给Traversable

您需要做的是:

$data = json_decode($j,true);

这将使对象成为关联数组,与foreach兼容,并且很可能与代码的其余部分兼容。

答案 1 :(得分:1)

当有一定数量的孩子时,你可以使用嵌套的foreach循环:

$json = '[{"name":"Ta","def":"somestring"},{"name":"WSCall","def":"somestring"},    {"name":"manual","def":"somestring"}]';
$decode = json_decode($json, true);

foreach ($decode as $k1 => $v1) {
    foreach ($v1 as $k2 => $v2) {
        echo "$k2: $v2, ";
    }
    echo "<br>";
}

它将输出:

name: Ta, def: somestring, <br>
name: WSCall, def: somestring, <br>
name: manual, def: somestring, <br>

答案 2 :(得分:0)

$j= '[{"name":"Ta","def":"somestring"},{"name":"WSCall","def":"somestring"},{"name":"manual","def":"somestring"}]';

$data = json_decode($j,true);

foreach($data as $key=>$val){
 foreach($val as $k=>$v){
   echo "Key :".$k."  Value :".$v."<br />";
 }
}