Toby Caulk
Toby Caulk

Reputation: 276

Print out JSON with multiple arrays

I have this JSON string that has been converted into a PHP array:

Array (
    [textfield] => Array (
        [elements] => Array (
            [0] => Array (
                [type] => textField
            )
        )
        [title] => textfield
    )
    [textarea] => Array (
        [elements] => Array (
            [0] => Array (
                [type] => textArea
            )
        )
        [title] => textarea
    )
) textfield

And I'm trying to loop through it and print out the type and title of each array. This is what I have so far:

foreach($inputs as $key => $jsons) {
    foreach($jsons as $key => $value) {
        echo $value;
    }
}

But that only prints out the title. Note, I do actually need to loop through the array and get all the values because I need to use them, I know I could use print_r to just dump the array but that's not what I need!

Upvotes: 2

Views: 209

Answers (2)

Rob W
Rob W

Reputation: 9142

Here's an easy way... but without seeing more of what you're trying to do, who knows if this will even work.

foreach($json as $key => $value) {
  $elements = $value['elements'];
  foreach($elements as $key => $element) {
    echo "$key = {$element['type']}\n";
  }
  $title = $value['title'];
  echo "$key = $title\n";
}

Upvotes: 2

anuj arora
anuj arora

Reputation: 831

foreach($inputs as $key => $jsons) {
    foreach($jsons as $key1 => $value) {
          if( $key1 == "title" ) {
                echo "TITLE :-".$value;
          } else if( is_array($value) {
                foreach($value as $key2 => $value2) {
                     echo "Type :".$value;
                }
          }
     }
}

Upvotes: 1

Related Questions