peter siow
peter siow

Reputation: 13

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 ?

Upvotes: 1

Views: 81

Answers (2)

Mihai Matei
Mihai Matei

Reputation: 24276

You can use array_walk_recursive:

foreach ($array as $sentence) {

    $string = '';

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

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

Upvotes: 0

cske
cske

Reputation: 2243

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

Upvotes: 1

Related Questions