0

您好,我不知道如何遍历这个 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'];

}

提前致谢

4

3 回答 3

1

好像您在数组中有一个对象。因此,您将需要遍历数组并获取每个对象。只需 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方式)。

于 2013-08-22T16:09:33.403 回答
1

用于json_decode将json对象转换为数组;然后用于foreach循环遍历数组。那应该行得通。

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

这应该会给你一些想法。

于 2013-08-22T16:09:57.417 回答
0

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

代码:

$json = json_decode($string, true);

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

工作演示!

于 2013-08-22T16:10:27.237 回答