How to access JSON decoded array in PHP - php

I returned an array of JSON data type from javascript to PHP, I used json_decode($data, true) to convert it to an associative array, but when I try to use it using the associative index, I get the error "Undefined index" The returned data looks like this
array(14) { [0]=> array(4) { ["id"]=> string(3) "597" ["c_name"]=> string(4) "John" ["next_of_kin"]=> string(10) "5874594793" ["seat_no"]=> string(1) "4" }
[1]=> array(4) { ["id"]=> string(3) "599" ["c_name"]=> string(6) "George" ["next_of_kin"]=> string(7) "6544539" ["seat_no"]=> string(1) "2" }
[2]=> array(4) { ["id"]=> string(3) "601" ["c_name"]=> string(5) "Emeka" ["next_of_kin"]=> string(10) "5457394839" ["seat_no"]=> string(1) "9" }
[3]=> array(4) { ["id"]=> string(3) "603" ["c_name"]=> string(8) "Chijioke" ["next_of_kin"]=> string(9) "653487309" ["seat_no"]=> string(1) "1" }
Please, how do I access such array in PHP? Thanks for any suggestion.

As you're passing true as the second parameter to json_decode, in the above example you can retrieve data doing something similar to:
$myArray = json_decode($data, true);
echo $myArray[0]['id']; // Fetches the first ID
echo $myArray[0]['c_name']; // Fetches the first c_name
// ...
echo $myArray[2]['id']; // Fetches the third ID
// etc..
If you do NOT pass true as the second parameter to json_decode it would instead return it as an object:
echo $myArray[0]->id;

$data = json_decode($json, true);
echo $data[0]["c_name"]; // "John"
$data = json_decode($json);
echo $data[0]->c_name; // "John"

$data = json_decode(...);
$firstId = $data[0]["id"];
$secondSeatNo = $data[1]["seat_no"];
Just like this :)

As you're passing true as the second parameter to json_decode, in the above example you can retrieve data doing something similar to:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>

This may help you!
$latlng='{"lat":29.5345741,"lng":75.0342196}';
$latlng=json_decode($latlng,TRUE); // array
echo "Lat=".$latlng['lat'];
echo '<br/>';
echo "Lng=".$latlng['lng'];
echo '<br/>';
$latlng2='{"lat":29.5345741,"lng":75.0342196}';
$latlng2=json_decode($latlng2); // object
echo "Lat=".$latlng2->lat;
echo '<br/>';
echo "Lng=".$latlng2->lng;
echo '<br/>';

When you want to loop into a multiple dimensions array, you can use foreach like this:
foreach($data as $users){
foreach($users as $user){
echo $user['id'].' '.$user['c_name'].' '.$user['seat_no'].'<br/>';
}
}

Related

Retrieving data from a multidimensional array object stdClass

How can I get out of this likeCount? Thanks cause I have no idea how to do it
https://gdata.youtube.com/feeds/api/videos/f4LxBKN9ank?v=2&alt=jsonc
The array
object(stdClass)#1 (2) {
["apiVersion"]=>
string(3) "2.1"
["data"]=>
object(stdClass)#2 (19) {
["id"]=>
string(11) "f4LxBKN9ank"
["uploaded"]=>
string(24) "2014-01-26T02:34:24.000Z"
["title"]=>
string(25) "League of Legends : Worth"
["content"]=>
object(stdClass)#5 (3) {
["5"]=>
string(74) "https://www.youtube.com/v/f4LxBKN9ank?version=3&f=videos&app=youtube_gdata"
["1"]=>
string(102) "rtsp://r5---sn-4g57kuee.c.youtube.com/CiILENy73wIaGQl5an2jBPGCfxMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"
["6"]=>
string(102) "rtsp://r5---sn-4g57kuee.c.youtube.com/CiILENy73wIaGQl5an2jBPGCfxMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"
}
["duration"]=>
int(78)
["aspectRatio"]=>
string(10) "widescreen"
["rating"]=>
float(4.921824)
["likeCount"]=>
string(5) "14147"
["ratingCount"]=>
int(14429)
["viewCount"]=>
int(678017)
}
}
You can do like that.
<?php
$data = #file_get_contents("http://gdata.youtube.com/feeds/api/videos/f4LxBKN9ank?v=2&alt=jsonc");
$realdata = json_decode($data);
$likecount = $realdata->data->likeCount;
// Sample data
$data = '{"apiVersion":"2.1","data":{"id":"f4LxBKN9ank","uploaded":"2014-01-26T02:34:24.000Z","updated":"2014-03-01T16:48:02.000Z","uploader":"videogamedunkey","category":"Comedy","title":"League of Legends : Worth","description":"Allow 3-5 weeks for your burrito to arrive.\n\nhttps://www.youtube.com/watch?v=YxeOLw1npuo&list=FLsvn_Po0SmunchJYOWpOxMg&index=1","thumbnail":{"sqDefault":"https://i1.ytimg.com/vi/f4LxBKN9ank/default.jpg","hqDefault":"https://i1.ytimg.com/vi/f4LxBKN9ank/hqdefault.jpg"},"player":{"default":"https://www.youtube.com/watch?v=f4LxBKN9ank&feature=youtube_gdata_player","mobile":"https://m.youtube.com/details?v=f4LxBKN9ank"},"content":{"5":"https://www.youtube.com/v/f4LxBKN9ank?version=3&f=videos&app=youtube_gdata","1":"rtsp://r5---sn-jc47eu7e.c.youtube.com/CiILENy73wIaGQl5an2jBPGCfxMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp","6":"rtsp://r5---sn-jc47eu7e.c.youtube.com/CiILENy73wIaGQl5an2jBPGCfxMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"},"duration":78,"aspectRatio":"widescreen","rating":4.921824,"likeCount":"14147","ratingCount":14429,"viewCount":678049,"favoriteCount":0,"commentCount":1497,"accessControl":{"comment":"allowed","commentVote":"allowed","videoRespond":"moderated","rate":"allowed","embed":"allowed","list":"allowed","autoPlay":"allowed","syndicate":"allowed"}}}';
// Decode $data into an array
$json = json_decode($data, true);
// Get the like count from data/likeCount in the array
$likeCount = $json["data"]["likeCount"];
// Display the likeCount
echo $likeCount; // 14147
$json = json_decode($data, true) decodes the data in $data into an array called $json. This array has a sub-array whose key is "data", and this sub-array contains the like count under the key "likeCount". Therefore, the like count can be accessed by chaining indexes together: $likeCount = $json["data"]["likeCount"])

parsing json values with php from an array

I have an array and i am trying to decode and parse the json values,
can't get it right.
Here's the info:
$send[0] :
Array ( [0] => {"message-count":"1","messages":[{"error-text":"Missing to param","status":"2"}]} )
var_dump(json_decode($v_send[0]));
/* output
json Dunmpobject(stdClass)#1 (2) { ["message-count"]=> string(1) "1" ["messages"]=> array(1) { [0]=> object(stdClass)#2 (2) { ["error-text"]=> string(16) "Missing to param" ["status"]=> string(1) "2" } } }
*/
var_dump(json_decode($v_send[0], true));
/* output
array(2) { ["message-count"]=> string(1) "1" ["messages"]=> array(1) { [0]=> array(2) { ["error-text"]=> string(16) "Missing to param" ["status"]=> string(1) "2" } } }
*/
$json=json_decode($v_send[0]);
echo "Start:";
echo "<br/><br/>";
// To loop
if (!is_array($json)) die('...');
foreach ($json as $key=>$tts_result)
{
echo $tts_result->callid;
echo "<br/><br/>";
echo $tts_result->to;
echo "<br/><br/>";
echo $tts_result->messages["status"];
echo "<br/><br/>";
echo $tts_result->error-text;
}
the echo in the loop gives empty result. anyone can help ?
$json is not an array, it's an object (of class stdClass).
If you want arrays, pass true as second argument of json_decode:
$json = json_decode($v_send[0], true);

PHP: Foreach an array won't output

When I dump the variable it has a data:
var_dump($result);
object(stdClass)#2 (5) { ["user_id"]=> string(1) "1" ["username"]=> string(6) "user_name" ["email"]=> string(14) "test#mail.com" ["password"]=> string(32) "password" ["test"]=> string(1) "1" }
But when I use foreach no value has return except if I just echo $data; but I want to be specific to the value I want to get.
foreach($result as $data){
echo $data->use_id;
echo $data->username;
}
Why there is no returned value?
Try this : json_decode converts json string to array. Ref: http://php.net/manual/en/function.json-decode.php
$array = json_decode($result, true);
echo "<pre>";
print_r($array);
You can use foreach to $array and echo the result.
You don't need to iterate over the object. Just do this.
echo $result->user_id;
echo $result->username;
With the sample you provided you are treating each property in $result as an object and looking for user_id and user_name (which don't exist).
As you wrote:
var_dump($result);
object(stdClass)#2 (5) { ["user_id"]=> string(1) "1" ["username"]=> string(6) "user_name" ["email"]=> string(14) "test#mail.com" ["password"]=> string(32) "password" ["test"]=> string(1) "1" }
So the result is an object itself. so if you want specify and fetch exact variable, there's no need to iterate it!

Create JSON object from PHP MySQL result

I want to create a JSON object from my MySQL results with PHP so I can pass it to JavaScript. I don't quite understand the difference between JSON array and JSON object.
This is how I do it. But is there a better way? This is the array way I believe?
$json = array();
while($r=mysql_fetch_array($res)){
$json['firstname'] = $r['firstname'];
$json['lastname'] = $r['lastname'];
}
echo json_encode($json);
I want to be able to get the info from JavaScript, by selecting all first names only If I wish etc..
you can try this, fetch data and push to array, then echo that array
$info=array();
while($row = mysql_fetch_array($res,MYSQL_ASSOC)){
array_push($info,$row);
}
echo json_encode($info);
would return
array(2) { [0]=> array(3) { ["id"]=> string(1) "1" ["firstname"]=> string(3) "foo" ["lastname"]=> string(3) "bar" } [1]=> array(3) { ["id"]=> string(1) "2" ["firstname"]=> string(3) "foo" ["lastname"]=> string(3) "bar" } }
json
[{"id":"1","firstname":"foo","lastname":"bar"},{"id":"2","firstname":"foo","lastname":"bar"}]
Well this would encode every row, with each row being the JSON Object:
$json = array();
while($r=mysql_fetch_array($res)){
$json[] = $r;
}
echo json_encode($json);

Get information from JSON

So currently I am doing this..
function get_info($data)
{
$json = file_get_contents("http://site.com/".$data.".json");
$output = json_decode($json, true);
return $output;
}
which is fine and returns everything like this:
array(1) { ["allocation"]=> array(20) { ["carrier_ocn"]=> string(4) "6664" ["available_on"]=> NULL ["status"]=> string(9) "allocated" ["access_type"]=> string(8) "wireless" ["ratecenter"]=> string(9) "CHARLOTTE" ["lat"]=> float(35.2270869) ["contaminations"]=> NULL ["city"]=> string(9) "CHARLOTTE" ["lng"]=> float(-80.8431267) ["current_on"]=> string(10) "2010-04-28" ["block_code"]=> NULL ["npa"]=> int(704) ["geo_precision"]=> int(4) ["nxx"]=> int(291) ["assigned_on"]=> NULL ["country"]=> string(2) "US" ["region"]=> string(2) "NC" ["ratecenter_formatted"]=> string(9) "Charlotte" ["carrier"]=> string(20) "SPRINT SPECTRUM L.P." ["effective_on"]=> NULL } }
How can I make that return only selected values like "ratecenter_formatted". I just want to get "Charlotte" from the above dump. How would I do this?
Thank you in advance!
Hmmm, just fish it out from the array? json_decode() on a JSON array will give you a PHP array that you can use just like any other array in PHP (in this case an associative one).
$output = get_info($data);
echo $output['allocation']['ratecenter_formatted'];
You would still need to decode the entire JSON string to get single values from it, there's no way to decode only certain values.
You could just return the values you want in the php function:
function get_info($data)
{
$json = file_get_contents("http://site.com/".$data.".json");
$output = json_decode($json, true);
return array(
'ratecenter_formatted' => $output['allocation']['ratecenter_formatted']
);
}

Categories