如何在PHP中循环回显嵌套数组中的所有值

时间:2016-10-13 06:21:47

标签: php arrays json loops

我有像这样的json数据

    {
      "Sentence": {
        "Subject": {
          "Name": "Tom"
        },
        "Verb": {
          "verb1": "is",
          "verb2": "eating"
        },
        "Object": {
          "Fruit": "Banana"
        }
      },
     "Sentence2": {
        "Subject": {
          "Name": "Mary"
        },
        "Verb": {
          "verb1": "eats",
        },
        "Object": {
          "Fruit": "Apple"
        }
      }

    }

然后,我通过

将其转换为数组
$array = json_decode($json,true);

我得到了阵列,

    array(2) {
      ["Sentence"]=>
      array(3) {
        ["Subject"]=>
        array(1) {
          ["Name"]=>
          string(3) "Tom"
        }
        ["Verb"]=>
        array(2) {
          ["verb1"]=>
          string(2) "is"
          ["verb2"]=>
          string(6) "eating"
        }
....

现在,我想只得到结果, 喜欢

"Tom is eating banana"
"Mary eats Apple".

两句话的结构不一样,我该怎么办?

2 个答案:

答案 0 :(得分:1)

如果嵌套级别未知

,请使用此选项
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$json = '{ "Sentence": { "Subject": { "Name": "Tom" }, "Verb": { "verb1": "is", "verb2": "eating" }, "Object": { "Fruit": "Banana" } }, "Sentence2": { "Subject": { "Name": "Mary" }, "Verb": { "verb1": "eats"},"Object": {"Fruit": "Apple"}}}';

$Sentences = json_decode($json,true);

foreach ($Sentences as $p => $words) {
    $out = [];
    array_walk_recursive($words,function ($v,$k) use (&$out){
       if (!is_array($v)) {
           $out[] = $v;
       }
    });
    echo $p,': ',implode(' ',$out),"\n";
}

答案 1 :(得分:0)

您可以使用array_walk_recursive

foreach ($array as $sentence) {

    $string = '';

    array_walk_recursive($sentence, function($item, $key) use (&$string) {
        $string .= $item . ' ';
    });

    echo $string . '<br />';
}