1

I have a array which comes through an POST request from javascript/jquery. In php the array content is as follows:

[{"name":"Ta","def":"somestring"},{"name":"WSCall","def":"somestring"},{"name":"manual","def":"somestring"}]

How do I iterate over this array to get the keys and values?

When I do: json_decode($_POST['shape_defs'])

How do I iterate over this array. Doing foreach says:

Invalid argument supplied for foreach()

1
  • 1
    Did you json decoded your result? Commented Apr 4, 2014 at 18:47

3 Answers 3

2

While the (current) other two answers do get working code, they fail to address why you get the error you do.

$data = json_decode($j);
var_dump($data);

This will produce an object, with keys as properties. An object is not valid to be passed to foreach unless it implements Traversable.

What you need to do is:

$data = json_decode($j,true);

This will make objects be associative arrays instead, which are compatible with foreach and most likely the rest of your code.

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't get any error without passing the second boolean parameter? If you do var_dump($data) it contains array of objects which is valid in foreach
1

When there's a definite number of children, you can use nested foreach-loops:

$json = '[{"name":"Ta","def":"somestring"},{"name":"WSCall","def":"somestring"},    {"name":"manual","def":"somestring"}]';
$decode = json_decode($json, true);

foreach ($decode as $k1 => $v1) {
    foreach ($v1 as $k2 => $v2) {
        echo "$k2: $v2, ";
    }
    echo "<br>";
}

It will output this:

name: Ta, def: somestring, <br>
name: WSCall, def: somestring, <br>
name: manual, def: somestring, <br>

Comments

0
$j= '[{"name":"Ta","def":"somestring"},{"name":"WSCall","def":"somestring"},{"name":"manual","def":"somestring"}]';

$data = json_decode($j,true);

foreach($data as $key=>$val){
 foreach($val as $k=>$v){
   echo "Key :".$k."  Value :".$v."<br />";
 }
}

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.