PHP loop through nested JSON to find value - php

I am trying to loop through nested JSON data to find a name with a specific string and extract the string value associated with that. In this case the name string is "myKey" and the value string is "12345678".
After looking at several similar questions and documentation, I have tried different approaches such as doing it with objects or associative arrays, but still end up not being able to get to the information I want or receive errors.
Types of errors:
Notice: Array to string conversion
Warning: Invalid argument supplied for foreach()
Trying to get property of non-object
Here is a snippet of the decoded JSON using $myObj = json_decode($result);
object(stdClass)#4 (3) {
["info"]=>
object(stdClass)#5 (10) {
.
.
.
}
["stuff"]=>
array(1) {
.
.
.
}
["result"]=>
array(3) {
[0]=>
object(stdClass)#7 (3) {
["name"]=>
["value"]=>
["description"]=>
}
[1]=>
object(stdClass)#8 (2) {
["name"]=>
string(4) "Units"
["value"]=>
array(2) {
[0]=>
array(6) {
[0]=>
object(stdClass)#9 (3) {
.
.
.
}
.
.
.
[5]=>
object(stdClass)#14 (2) {
["name"]=>
string(10) "Components"
["value"]=>
array(1) {
[0]=>
array(14) {
[0]=>
object(stdClass)#15 (3) {
.
.
.
}
[1]=>
object(stdClass)#16 (3) {
["name"]=>
string(5) "myKey"
["value"]=>
string(8) "12345678"
["description"]=>
}
.
.
.
Here is a snippet of the PHP code I tried:
$myObj = json_decode($result);
// or I have tried
// $myObj = json_decode($result, true);
// here are different snippets of code I tried
foreach($myObj->result as $test) {
echo '<pre>';
print_r($test->name);
echo "<br>";
if ($test->name == "Units") {
$resultName = $test->name;
echo $resultName . "<br>";
}
echo '</pre>';
}
/*
foreach($myObj->result as $test) {
echo $test . "<br>";
foreach($test->name as $test1) {
echo $test1 . "<br>";
foreach($test1->value as $test2) {
echo $test2 . "<br>";
}
}
}
*/
/*
foreach($myObj->result as $test) {
if (($test->name) == "Units") {
// grab the value that corresponds to the name
$units = $test->name;
if (($units->name) == "Components") {
$components = $units->name;
print_r($components);
}
}
}
*/
I can access what I need directly, by saying:
print_r($myObj->result[1]->value[0][5]->value[0][1]->name);
print_r($myObj->result[1]->value[0][5]->value[0][1]->value);
but the location of the value may vary, so I need to find the names of the objects by looping
Can anyone provide a better approach using objects (or possibly even associative arrays)?
UPDATED TO INCLUDE SNIPPET OF ORIGINAL JSON (before decode)
string(21420) "{
"info": {
.
.
.
},
"stuff": [{
"name":
"type":
.
.
.
}],
"result": [
{
"name":
"value":
"description":
},
{
"name": "Units",
"value": [
[
{
"name":
"value":
"description":
},
.
.
.
{
"name": "Components",
"value": [
[
{
"name":
"value":
"description":
},
{
"name": "myKey",
"value": "12345678",
"description":
},
.
.
.
] (end inner Components value)
] (end outer Components value)
] (end inner Units value)
] (end outer Units value)
} (end results Units)
] (end result)
} (end opening)

It feels like you need some recursive function (a function that calls itself until it finds the the result) to find the value within the nested array.
Take a look at Recursive array_search
Of course you will have to change the function in that question, but I have similar issue once and it was very userful.

Below is the code for encoding and decoding. hope this helps you
//Encoding
//Array Values
$a1=array("name"=>"abc", "value"=>"def", "description"=>"ghi");
$a2=array("name"=>"jkl", "value"=>"mno", "description"=>"pqr");
$a3=array("name"=>"stu", "value"=>"wxy", "description"=>"zab");
//Array of Value Arrays
$info=array($a1, $a2, $a3);
$result=array($a1, $a2, $a3);
$stuff=array($a1, $a2, $a3);
//The Main Enclosed Array
$main=json_encode(array("info"=>$info, "result"=>$result, "stuff"=>$stuff));
//Decoding
//Fetching the name from result's $a1 array
$main_array=json_decode($main);
echo $main_array->result[1]->name; //Displays jkl

Related

JSON decode only one data php

I have JSON data:
[
{
"title": "red",
},
{
"title": "blue",
},
{
"title": "yellow",
},
]
I want to get only first data, red.
I try with this
...
$json_output=curl_exec($ch);
$mydata = json_decode($json_output);
$result = $mydata->title;
echo $result[1];
and
$result = $mydata->title[1];
but dont work.
How i can get only first "title" data from this json?
$json_output=curl_exec($ch);
$mydata = json_decode($json_output);
$result = $mydata[0]->title;
echo $result;
According to PHP's manual, json_decode returns the value encoded in JSON in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the JSON cannot be decoded or if the encoded data is deeper than the recursion limit.
<?php
$json_output = '[{ "title": "red" }, { "title": "blue" }, { "title": "yellow" }]';
$mydata = json_decode($json_output);
var_dump($mydata);
/* Output:
array(3) {
[0]=>
object(stdClass)#1 (1) {
["title"]=>
string(3) "red"
}
[1]=>
object(stdClass)#2 (1) {
["title"]=>
string(4) "blue"
}
[2]=>
object(stdClass)#3 (1) {
["title"]=>
string(6) "yellow"
}
}
*/
echo $mydata[0]->title;
// Output: red
?>
When 2nd parameter is TRUE, returned objects will be converted into associative arrays.
<?php
$json_output = '[{ "title": "red" }, { "title": "blue" }, { "title": "yellow" }]';
$mydata = json_decode($json_output, TRUE);
var_dump($mydata);
/* Ouput:
array(3) {
[0]=>
array(1) {
["title"]=>
string(3) "red"
}
[1]=>
array(1) {
["title"]=>
string(4) "blue"
}
[2]=>
array(1) {
["title"]=>
string(6) "yellow"
}
}
*/
echo $mydata[0]['title'];
// Output: red
?>
On a side note, accessing elements within an object that contain any character not allowed under PHP's naming convention can be done by wrapping the index with a curly bracket.
<?php
$json_output = '[{ "h1-title": "red" }, { "h1-title": "blue" }, { "h1-title": "yellow" }]';
$mydata = json_decode($json_output);
var_dump($mydata);
/* Output:
array(3) {
[0]=>
object(stdClass)#1 (1) {
["h1-title"]=>
string(3) "red"
}
[1]=>
object(stdClass)#2 (1) {
["h1-title"]=>
string(4) "blue"
}
[2]=>
object(stdClass)#3 (1) {
["h1-title"]=>
string(6) "yellow"
}
}
*/
echo $mydata[0]->{'h1-title'};
// Output: red
?>
First of all your JSON is not valid. You can use this validator to check if your JSON is valid. It should look like the following:
[
{
"title": "red"
},
{
"title": "blue"
},
{
"title": "yellow"
}
]
There are two ways of accessing the JSON object:
Array of objects:
$mydata = json_decode($json_output);
$title = $mydata[0]->title; // red
Associative array:
$mydata = json_decode($json_output, true);
$title = $mydata[0]['title']; // red
See json_decode() for more information.

convert php array to javascript literal object

I have a php page which returns a php array as the following
array(6) {
[0]=>
array(2) {
["cityName"]=>
string(10) "Ananindeua"
[0]=>
string(10) "Ananindeua"
}
[1]=>
array(2) {
["cityName"]=>
string(8) "An�polis"
[0]=>
string(8) "An�polis"
}
[2]=>
array(2) {
["cityName"]=>
string(8) "Anderson"
[0]=>
string(8) "Anderson"
}
[3]=>
array(2) {
["cityName"]=>
string(6) "Angers"
[0]=>
string(6) "Angers"
}
[4]=>
array(2) {
["cityName"]=>
string(9) "Angoul�me"
[0]=>
string(9) "Angoul�me"
}
[5]=>
array(2) {
["cityName"]=>
string(6) "Anshan"
[0]=>
string(6) "Anshan"
}
}
I want to use this array in another page to do some ajax, and I want to encode the resulat into a JSON as the following :
{
"cityName": "Anshan",
"cityName": "Angoul�me",
"cityName": "Anderson",
"cityName": "An�polis",
"cityName": "Ananindeua"
}
but Instead I get only one value, which is the last value :
{
"cityName": "Anshan"
}
This is the code I tried :
<?php
$connexion = new PDO("mysql:host=localhost;dbname=world", 'root', 'toor');
$statement = $connexion->prepare("SELECT cityName FROM cities WHERE cityName LIKE '" . $_POST['cityName'] . "%'");
$statement->execute();
$resultats = $statement->fetchAll();
foreach($resultats as $city) {
$output[key($city)] = current($city);
}
echo json_encode($output, 128);
?>
So how can I solve this problem ?
Edit :
I tried to get only cities names, and push them into an array, when I do a var_dump() for this array this is what I get :
array(6) {
[0]=>
string(10) "Ananindeua"
[1]=>
string(8) "An�polis"
[2]=>
string(8) "Anderson"
[3]=>
string(6) "Angers"
[4]=>
string(9) "Angoul�me"
[5]=>
string(6) "Anshan"
}
But when I did a json_encode() I don't get anything, so I tried to do a var_dump(json_encode($output)); and I get this :
bool(false)
In the second time I tried to create a table manually :
$a = array("Ananindeua","Anápolis","Anderson","Angers","Angoulême","Anshan" );
and it worked.
But why the first array won't encode !
Your desired output is not valid/conceivable either as a PHP associative array or JSON because in both cases, you have duplicate keys.
You're just overwriting the cityName key with each iteration. Push to an array instead:
foreach($resultats as $city) {
$output[] = current($city);
}
echo json_encode($output, 128);
Output:
[
"Anshan",
"Angoulme",
"Anpolis"
]
Or if you want an object for each city, which is useful if you want other properties:
foreach($resultats as $city) {
$output[] = array(
'cityName' => current($city)
);
}
echo json_encode($output, 128);
Output:
[
{
"cityName" : "Anshan",
},
{
"cityName" : "Angoulme",
},
{
"cityName" : "Anpolis"
}
]
Side note: if you don't need the numerical keys from the PDO fetch call, consider using the PDO::FETCH_ASSOC fetch style, to bring back only associative keys:
$resultats = $statement->fetchAll(PDO::FETCH_ASSOC);
The json you're expecting doesn't look right. It should be:
[
{"cityName": "Anshan"},
{"cityName": "Angoul�me"},
{"cityName": "Anderson"},
{"cityName": "An�polis"},
{"cityName": "Ananindeua"}
]
and to generate this you need code like this:
foreach($resultats as $city) {
$item = new stdClass();
$item.cityName = current($city);
$output[] = item;
}
Your array's key is same (cityName), so the value getting replaced on each assignment.
use a numeric array, or another method that differentiating the key
e.g.,
foreach($resultats as $city) {
$output['cityName'][] = current($city);
}
output will be
{"cityName":
[
"Anshan",
"Angoulme",
"Anpolis"
]
}
The problem was that the table which I populate from database contains some accented characters, so the json_encode() failing.
The solution was to add charset=UTF8 in the first parameter of the PDO instance.
$connexion = new PDO("mysql:host=localhost;dbname=world;charset=UTF8", 'root', 'toor');

parse, filter and display multi-level json using php

Completely new to JSON and am tasked with filtering/sorting a remote JSON using php and embedding formatted results into a CMS.
The data structure looks like this:
"Categories":[
{
"Name":"Americas",
"ID":"12345",
"Countries":[
{
"Name":"Argentina",
"Partners":[
{
"Country":"Argentina",
"ID":"4321",
"LogoUrl":"logo1.jpg",
"Title":"Company A",
"AddressBlock":"123 Main Street",
"Phone":"444-555-1212",
"TollFree":"",
"Email":"info#CompanyA.com",
"Url":"http://www.CompanyA.com/",
"IsVisible":true,
"IsDistributor":false
}
]
},
{
"Name":"Brazil",
"Partners":[
{
"Country":"Brazil",
"ID":"5432",
"LogoUrl":"logo2.jpg",
"Title":"Company B",
"AddressBlock":"54 Center Street",
"Phone":"234-567-3600",
"TollFree":"",
"Email":"info#CompanyB.com",
"Url":"http://www.CompanyB.com",
"IsVisible":true,
"IsDistributor":false
},
"Name":"Canada",
"Partners":[
{
"Country":"Canada",
"ID":"Company C",
"LogoUrl":"logo3.Company C",
"AddressBlock":"1 Mll Road Floor 27\r\nCanton, ON",
"Phone":"555-66-7777",
"TollFree":"",
"Email":"info#CompanyC.com",
"Url":"http://www.CompanyC.com",
"IsVisible":true,
"IsDistributor":false
},
]
}
]
}
]
Ideally I would like to store the key/value pairs in an array and then print them out as a list sorted alphabetically. Each Country could have multiple entries and those set to "IsVisible:false" would need to be hidden.
I did some searching here and I could get to the data source but the array is not
'exploded' or looped through its dimensions by php and get this returned:
Categories:Array
using this code:
$string = file_get_contents("https://myURL.securekey");
foreach ($json_a as $key => $value)
{
foreach($value as $v)
{
echo $v." ";
}
}
Any help would be GREATLY appreciated.
Thanks!
Edited: So by using the below:
$string = file_get_contents('https://secure.json');
$json = json_decode($string, true);
foreach($json as $fieldIndex => $fields) {
foreach($fields as $valueIndex => $envelope) {
foreach($envelope as $valueEntry) {
foreach($valueEntry as $key => $value) {
if ($key == "Name") {
echo $value;
}
printf("%d - %d - %s: '%s'\n", $key, $value);
$build[$valueIndex][$key]=$value;
}
}
}
}
var_dump($build);
I get the following output:
0 - 0 - 0: 'Array' 0 - 0 - 1: 'Array' 0 - 0 - 2: 'Array' 0 - 0 - 3: 'Array' 0 - 0 - 4: 'Array' 0 - 0 - 5: 'Array' array(1) { [0]=> array(6) { [0]=> array(2) { ["Name"]=> string(9) "Argentina" ["Partners"]=> array(1) { [0]=> array(11) { ["Country"]=> string(9) "Argentina" ["ID"]=> string(36) "4d93" ["LogoUrl"]=> string(52) "http://www.aaa.com/images/partners/aaa.jpg" ["Title"]=> string(14) "Company S.A." ["AddressBlock"]=> string(118) "Main Street - Dock 8 12435- Anytown USA" ["Phone"]=> string(17) "(444) 123-4567" ["TollFree"]=> string(0) "" ["Email"]=> string(28) "info#aaa.com" ["Url"]=> string(35) "http://www.aaaa.com/" ["IsVisible"]=> bool(true) ["IsDistributor"]=> bool(false) } } }
But still unsure as to how to reference the specific name/values to echo them where needed. I assume maybe something like:
if ($key == "Title") {
echo "Title: " . $key . "<br />";
} esleif ($key == "Country") {
echo $value;
}
but am stuck on a) where to place it in the loop so it actually grabs the values at the right level and b) the syntax (which must be off because I can still only see anything with a var_dump at the end rather than echo out the values from within the loop.

Facebook JSON array

How do I display the data->name?
{
"data": [
{
"name": "Aasdada",
"category": "asdasd",
"id": "2342342342",
"created_time": "2012-11-28T03:56:00+0000"
}
],
"paging": {
"next": "https://graph.facebook.com/&limit=5000&offset=5000&__after_id=12312"
}
}
I tried this but nothing comes out:
$user = json_decode(file_get_contents($graph_url), true);
echo("Hello " . $user->data->name);
//also tried this
echo("Hello " . $user[data]); //did not echo anything
echo("Hello " . $user->data[0]->name); //did not echo anything
$user->data[0]['name'] //still no luck
What could be the problem?
Anyways my code works with data that is not in array.
I'm just trying to make a simple if user liked page or not.
If data has no contents it means the user has not liked the page.
If it has data then it means the user has liked the page.
--edit--
So tried this out:
array(2) { ["data"]=> array(1) { [0]=> array(4) { ["name"]=> string(28) "Aasdda" ["category"]=> string(5) "asdad" ["id"]=> string(15) "3123123123" ["created_time"]=> string(24) "2012-11-28T03:56:00+0000" } } ["paging"]=> array(1) { ["next"]=> string(245) "https://graph.facebook.com/100023123123" } }
Try:
$user['data']['0']['name']
Try:
$user->data[0]['name']

json Problems to echo, arrays

I am working on a script, that will use steam api, and i selected to use json for the response format.
So i have used var_dump with and without jason_decode() and it appears to be ok.
But can't manage to print it out, or echo it.
Script that gets the json data
<?php
$id = $_GET['SteamId'];
$get = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=API_KEY_REMOVED_FOR_SECURITY&steamids=$id",true);
$data = json_decode($get);
//var_dump($data);
echo $data->realname;
?>
So, that i get using the var_dump with json_decode is this.
object(stdClass)#1 (1) { ["response"]=> object(stdClass)#2 (1) { ["players"]=> array(1) { [0]=> object(stdClass)#3 (15) { ["steamid"]=> string(17) "76561198053511970" ["communityvisibilitystate"]=> int(3) ["profilestate"]=> int(1) ["personaname"]=> string(9) "Undefined" ["lastlogoff"]=> int(1340978067) ["profileurl"]=> string(41) "http://steamcommunity.com/id/Heisteknikk/" ["avatar"]=> string(114) "http://media.steampowered.com/steamcommunity/public/images/avatars/5c/5c75278da69102d9c8290bccd1becbb4081954cd.jpg" ["avatarmedium"]=> string(121) "http://media.steampowered.com/steamcommunity/public/images/avatars/5c/5c75278da69102d9c8290bccd1becbb4081954cd_medium.jpg" ["avatarfull"]=> string(119) "http://media.steampowered.com/steamcommunity/public/images/avatars/5c/5c75278da69102d9c8290bccd1becbb4081954cd_full.jpg" ["personastate"]=> int(1) ["realname"]=> string(7) "Andreas" ["primaryclanid"]=> string(18) "103582791430704052" ["timecreated"]=> int(1322427688) ["loccountrycode"]=> string(2) "NO" ["locstatecode"]=> string(2) "09" } } } }
And the raw data from the json.
{
"response": {
"players": [
{
"steamid": "76561198053511970",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "Undefined",
"lastlogoff": 1340978067,
"profileurl": "http:\/\/steamcommunity.com\/id\/Heisteknikk\/",
"avatar": "http:\/\/media.steampowered.com\/steamcommunity\/public\/images\/avatars\/5c\/5c75278da69102d9c8290bccd1becbb4081954cd.jpg",
"avatarmedium": "http:\/\/media.steampowered.com\/steamcommunity\/public\/images\/avatars\/5c\/5c75278da69102d9c8290bccd1becbb4081954cd_medium.jpg",
"avatarfull": "http:\/\/media.steampowered.com\/steamcommunity\/public\/images\/avatars\/5c\/5c75278da69102d9c8290bccd1becbb4081954cd_full.jpg",
"personastate": 1,
"realname": "Andreas",
"primaryclanid": "103582791430704052",
"timecreated": 1322427688,
"loccountrycode": "NO",
"locstatecode": "09"
}
]
}
}
I've been searching around on google about printing the json using "echo $data->realname;".
So i don't know what i did wrong, so it canno't echo the data.
Intro
Hey there, this is a REALLY old question, but since there's no answer here.
You do have it right when it comes to decoding the JSON PHP has the built-in function json_decode which can easily decode the function for you:
$json = '{...}';
$obj = json_decode($json, [ASSOC_ARRAY = FALSE]);
The second Param you can set to bool for an associative array which would change mentions from:
$obj->response;
To
$obj['response'];
Response
Now you say you need the realname from the players, that would be as simple as getting it via the player's position in the array, or just looping through the array:
echo $obj->response->players[0]->realname; // Andreas
Or if you have multiple users:
for( $i = 0; $i < count($obj->response->players); $i++ ) {
echo $obj->response->players[$i]->realname;
}
Which would display all of the realname(s)

Categories