チャオ レテ チャオ レテ - 1 month ago 13
JSON Question

How to echo all the value in nested array by loop in PHP

I have the json data like this

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

}


Then , I convert it to array by

$array = json_decode($json,true);


And I got the array ,

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


Now , I want get the result only ,
like

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


The structure of the two sentence are not same, how can i do ?

Answer

Use this if nesting level unknown

<?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";
}
Comments