2016-10-13 59 views
1

迴響在嵌套數組中的所有值我有這樣如何通過循環在PHP

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

    } 

JSON數據。然後,我將其轉換爲陣列通過

$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". 

這兩句話的結構不一樣,我該怎麼辦?

回答

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"; 
} 
0

您可以使用array_walk_recursive

foreach ($array as $sentence) { 

    $string = ''; 

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

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

非常感謝你,但是我發現,一些數據仍然有嵌套數組,一些結果將是「他是陣列陣列「 –

+0

我改變了我的答案..它應該按預期工作 –