json_encode获取foreach对象的值

时间:2013-08-22 16:00:16

标签: php json

您好我无法弄清楚如何遍历此json编码数组并为每个对象获取其所有值。我需要将每个值作为自身的变量。

echo json_encode($formulars);

这是我在回声时得到的结果

[{"project_name":"polle","type":"support","title":"vi","reason":"prover","solution":"igen","comments":"okay ","date_stamp":"2013-08-20 14:06:37","used_time":132},{"project_name":"dolla","type":"support","title":"lolol","reason":"skl","solution":"dskal","comments":"kflafda ","date_stamp":"2013-08-20 14:11:36","used_time":210},{"project_name":"polle","type":"fejl","title":"lol","reason":"aksdl","solution":"fdjks","comments":"djsks ","date_stamp":"2013-08-20 14:13:27","used_time":1230}]

我尝试过这段代码,并设法从第一个对象中取出project_name,就是这样:

foreach ($formulars as $current => $project_name) {
        $project_name['project_name'];

    }

那么有什么方法可以为我的数组中的每个对象获取所有变量而不仅仅是project_name?

像这样:

foreach ($formulars as $current){ 
    $projectName = $current['project_name'];
    $type = $current['type'];
    $reason = $current['reason'];

}

提前致谢

3 个答案:

答案 0 :(得分:1)

使用json_decode将json对象转换为数组;然后使用foreach循环遍历数组。这应该有用。

<?php
    $arr_json = json_decode($formulars);
    foreach($arr_json as $key => $value)
        //Code to perform required actions
?>

这应该会给你一些想法。

答案 1 :(得分:0)

好像你在数组中有一个对象。因此,您需要遍历数组并获取每个对象。只需JSON_DECODE您的编码字符串如下。

也许:

$data = json_decode($formulars,true);
/* Since it's only one object inside the array, you could just select element zero, but I wil loop*/

//You should now be able to do this
foreach ($data as $current){ 
    $projectName = $current['project_name'];
    $type = $current['type'];
    $reason = $current['reason'];

 }

我循环的原因是因为数组中有一个对象(我认为是Javascript方式)。

答案 2 :(得分:0)

使用json_decode(使用TRUE获取关联数组)将JSON对象转换为关联数组。之后,您可以使用foreach循环遍历多维数组并打印所需的值。

代码:

$json = json_decode($string, true);

foreach ($json as $key => $value) {
  foreach($value as $key2 => $value2) {
    echo $value2."\n";
  }
}

<强> Working Demo!