1

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 ?

2 Answers 2

1

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";
}
Sign up to request clarification or add additional context in comments.

Comments

0

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 />';
}

2 Comments

Thank you very much , But I found that some data still have Nested Array , Some results will be "He is Array Array"
I've changed my answer.. it should work as expected now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.