2

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!

1
  • See my answer. I'll update it once you show how you need $elements[x]['type']. Commented Aug 11, 2015 at 13:56

2 Answers 2

2

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

5 Comments

This prints out the title element, but I also need to print out the type within each element of the elements array.
Updated answer for you.
It's complaining about a String to Array conversion where you echo the $element. Which makes no sense since that should loop through the array correct?
Ah, forgot that $element is an array.. fixed answer.
No problem.. Keep in mind that I have specified $element['type'] in a static manner... which may or may not work for you... but if $element will always have a type-keyed array item, then it should be fine.. just something to be aware of for the future.
1
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;
                }
          }
     }
}

Comments

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.