【问题标题】:How to echo all the value in nested array by loop in PHP如何在PHP中通过循环回显嵌套数组中的所有值
【发布时间】:2016-10-13 06:21:46
【问题描述】:

我有这样的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".

两个句子的结构不一样,怎么办?

【问题讨论】:

    标签: php arrays json loops


    【解决方案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";
    }
    

    【讨论】:

      【解决方案2】:

      你可以使用array_walk_recursive:

      foreach ($array as $sentence) {
      
          $string = '';
      
          array_walk_recursive($sentence, function($item, $key) use (&$string) {
              $string .= $item . ' ';
          });
      
          echo $string . '<br />';
      }
      

      【讨论】:

      • 非常感谢,但是我发现有些数据还是有嵌套数组,有些结果会是“他是数组数组”
      • 我已经改变了我的答案.. 它现在应该可以正常工作了
      猜你喜欢
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多