John R
John R

Reputation: 3026

PHP JSON Decode

I am trying to change a PHP script so that it can recieve a JSON object and work with that given JSON object. Everything works fine until I try to cycle trhough the converted-from-JSON-array-of-objects (aka 'stuff') with the for loop.

What am I doing wrong here:

$json = '{

    "foo":  "hi",
    "bar":  "bye"
    "stuff": [{"widget":"dd"},{"thing":"cc"},{"wcha":"dd"}] 
}';

$arr = json_decode($json, true);
$foo = $arr['foo']; //works fine
$bar = $arr['bar']; //works fine

//old way that worked:
//$stuff    = array("widget" => "dd", "thing" => "cc", "wcha" => "dd");
//new way that does not work:
$stuff = $arr['stuff'];
...

//This is where the problem is:
foreach ($stuff as $key => $value){...

The problem in the for loop is that $key is an integer (not the actual value) and $value is the word 'Array' (not the actual value).

Upvotes: 0

Views: 954

Answers (3)

AsTeR
AsTeR

Reputation: 7521

Change your JSON to

$json = '{
  "foo":  "hi",
  "bar":  "bye"
  "stuff": {"widget":"dd",
            "thing":"cc",
            "wcha":"dd"} 
}';

This way stuff contain another dictionary like structure.

In your example you are using [] who is used to encapsulate an array, not a json object, thus the integer you have are simply the indexes of the items {"widget":"dd"}, {"thing":"cc"} and {"wcha":"dd"} in your array. For your first iteration $value["widget"] should be equal to "dd".

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

It's doing exactly what it should. The problem is that you're not quite understanding it right.

"stuff" is an array of objects. So when you decode it, the resulting PHP array is this:

[stuff]=>
array(3)
  {
  [0]=>
  array(1)
    {
    [widget]=>string(2) "dd"
    }
  [1]=>
  array(1)
    {
    [thing]=>string(2) "cc"
    }
  [2]=>
  array(1)
    {
    [wcha]=>string(2) "dd"
    }
  }

So when you call foreach on it, you're getting the individual arrays from there.

I think your JSON should be:

"stuff": {"widget":"dd","thing":"cc","wcha":"dd"}

Either that, or your PHP code should be:

foreach($stuff as $element) {
    list($key,$value) = each($element);
    // now do stuff
}

Upvotes: 3

Authman Apatira
Authman Apatira

Reputation: 4054

of course $key is an integer =). [{"widget":"dd"},{"thing":"cc"},{"wcha":"dd"}] this is your array so key = 0 corresponds to the object {"widget":"dd"} and so fourth.

To get to the elements, try: $value->widget or $value->thing.

Since your objects in the stuff array don't all have the same members, you may wish to rethink the way you structure your object.

Upvotes: 2

Related Questions