There are so many JSON/PHP/Decode related post out there... but I am struggling here. I'm pretty sure I have built my JSON incorrectly, but I can't seem to see my mistake. Can anyone help?
{
"badging": [
{
"event": [
{
"eventName": "Covent Garden",
"numberOfRooms": "1",
"mainLang": "xx",
"timeZone": "saas"
}
]
},
{
"names": [
{
"id": "1",
"fName": "Daniel",
"pos": "King"
},
{
"id": "2",
"fName": "Dasha",
"pos": "Queen"
}
]
}
]
}
This is posted to a PHP page and json_decode is used
$json = $_POST['feed'];
$list = json_decode($json, TRUE);
And I feel I should be able to access the data like:
echo $list[1][2]['fName'];
or
echo $list->badging[1]->names[2]->fName;
but I can't seem to do it. thanks
Try $list['badging'][1]['names'][1]['fName'];
http://codepad.org/IdneHeDL
Also if you omit the true to json_decode then $list->badging[1]->names[1]->fName;
http://codepad.org/WXWkVqo1
It should be:
print($list["badging"][1]["names"][0]["fName"]); // outputs "Daniel"
print($list["badging"][1]["names"][1]["fName"]); // outputs "Dasha"
As per your JSON, by JSON_decode, we get
Array ( [badging] => Array ( [0] => Array ( [event] => Array ( [0] => Array ( [eventName] => Covent Garden [numberOfRooms] => 1 [mainLang] => xx [timeZone] => saas ) ) ) [1] => Array ( [names] => Array ( [0] => Array ( [id] => 1 [fName] => Daniel [pos] => King ) [1] => Array ( [id] => 2 [fName] => Dasha [pos] => Queen ) ) ) ) )
So, to access it, you need to it use
echo $list['badging'][1]['names'][0]['fName'];
Happy Coding :)
This is how your array looks.
array(1) {
["badging"]=>
array(2) {
[0]=>
array(1) {
["event"]=>
array(1) {
[0]=>
array(4) {
["eventName"]=>
string(13) "Covent Garden"
["numberOfRooms"]=>
string(1) "1"
["mainLang"]=>
string(2) "xx"
["timeZone"]=>
string(4) "saas"
}
}
}
[1]=>
array(1) {
["names"]=>
array(2) {
[0]=>
array(3) {
["id"]=>
string(1) "1"
["fName"]=>
string(6) "Daniel"
["pos"]=>
string(4) "King"
}
[1]=>
array(3) {
["id"]=>
string(1) "2"
["fName"]=>
string(5) "Dasha"
["pos"]=>
string(5) "Queen"
}
}
}
}
}
eg. echo $list['badging'][0]['event'][0]['eventName'];