I'm having problem with creating a foreach loop out of a JSON, I can't get the values out of the array correct, what am I doing wrong?
JSON:
[
{"Pages":{
"name":"Name 1",
"id":"3342939832994"
}
},
{"Pages":{
"name":"Name 2",
"id":"289051164453763"
}
}
]
PHP:
$json = $_POST['Publish'];
$json = $json->Pages
foreach($json as $key => $items) {
$id = $items->id;
$name = $items->id;
}
asked Aug 18, 2013 at 23:54
Kim
1,1486 gold badges21 silver badges41 bronze badges
2 Answers 2
Do it like this
$json = json_decode($_POST['Publish']);
json_decode - Takes a JSON encoded string and converts it into a PHP variable.
answered Aug 18, 2013 at 23:56
Roseann Solano
7682 gold badges8 silver badges13 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Brad Christie
obligatory docs:
json_decode. Also, depending, you may want to set $assoc = trueYou can use this code
<?php
$array = json_decode($_POST['Publish'], true);
foreach($array as $item) {
$id= $item['Pages']['id'];
$name = $item['Pages']['name'];
echo "id: $id <br/> name: $name <br/><br/>";
}
?>
answered Aug 19, 2013 at 3:25
Krimson
7,74911 gold badges65 silver badges104 bronze badges
Comments
lang-php
json_decodethe data. What's the next question?