2

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;     

    }
3
  • You forgot to json_decode the data. What's the next question? Commented Aug 18, 2013 at 23:55
  • 1
    Voting to close because "get the values out of the array correct" is not a problem description. Commented Aug 18, 2013 at 23:57
  • Thanks, I tried json_decode, but then the string gives med "null" Commented Aug 19, 2013 at 0:04

2 Answers 2

3

Do it like this

$json = json_decode($_POST['Publish']);

json_decode - Takes a JSON encoded string and converts it into a PHP variable.

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

1 Comment

obligatory docs: json_decode. Also, depending, you may want to set $assoc = true
0

You 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/>";
}

?>

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.