简体   繁体   中英

Retrieve value from a Json Array

I'm having difficulty in retrieving values from a Json array. I have a Json dataset that has been created using json_encode. This is how it appears after using json_decode and displaying using print_r:

Array ( [0] => stdClass Object ( [postID] => 1961 [postTitle] => Kiss My Fairy [previewThumb] => 2011/09/Kiss-My-Fairy-Ibiza-essentialibiza-2011_feature.jpg [blogContent] => Ibiza has always had a flair for the extravagant, inhibitions are checked in at the airport when the floods of tourists arrive and the locals have embraced a freedom of partying that has turned the quiet Mediterranean island into the Mecca... ) ) a_post_data_array = 1

The code that achieves this is as follows:

$post_data_URL = "http://myurl.com/news/scrape/facebook-like-chart-ID.php?post_name=kiss-my-fairy";

$post_data_response = file_get_contents($post_data_URL);  

$a_post_data_array=json_decode($post_data_response);  

I now simply need to retrieve some of the values from this array to use as variables. The array will only ever have 1 set of values. I'm using the following code but it isn't working.

echo "**** -- " . $a_post_data_array[post_title] . "<br>";

Can anyone please help? I'm sorry this is so basic. I've been searching online but can't find any examples of this.

echo "** -- " . $a_post_data_array[0]['post_title'];

There are multiple issues with your code:

  • First you should instruct json_decode to give you a pure array with $data = json_decode($response, TRUE);
  • Then the result array is a list, and you have to access the first element as $data[0]
  • The entry you want to access has the key postTitle , not post_title as your example code showed. (And unless that's a predefined constant won't work.)
  • And you need to put those array keys in quotes, like print $data[0]["postTitle"];

Turn up your error_reporting level for some development help.

try this PHP code:

//$post_data_response = file_get_contents("https://raw.github.com/gist/1245028/80e690bcbe6f1c5b46676547fbd396ebba97339b/Person_John.json");
//$PersonObject = json_decode($post_data_response);

// Get Person Object from JSON Source
$PersonObject = json_decode('{"ID":"39CA2939-38C0-4C4E-AE6C-CFA5172B8CEB","lastname":"Doe","firstname":"John","age":25,"hobbies":["reading","cinema",{"sports":["volley-ball","snowboard"]}],"address":{}}');

// Get data from Object
echo "Person ID => $PersonObject->ID<br>";
echo "Person Name => $PersonObject->firstname<br>";
echo "Person Lastname => $PersonObject->lastname<br>";  
echo "Person Age => $PersonObject->age<br>";
echo "Person Hobbies => " . $PersonObject->hobbies[0] . "<br>";     

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM