JSON decode only one data php - 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.

Related

Further data retrieving inside array of JSON using PHP

I have a JSON file I want to fill in a table, but can't quite figure out how to retrieve the data inside and loop it through an array to get in a table I made.
This is my JSON file: test.JSON:
{
"data":{
"Chair":{
"id":24,"key":"Chair","name":"Chair","title":"oak home made"
},
"Table":{
"id":37,"key":"Table","name":"Table","title":"round white table"
},
"Closet":{
"id":18,"key":"Closet","name":"Closet","title":"big and red"
},
"Sofa":{
"id":110,"key":"Sofa","name":"Sofa","title":"room for five persons"
}
},
"type":"furniture","version":"1.1.0"
}
Then with PHP I used this: test.PHP:
$url = 'test.json';
$result=file_get_contents($url);
$decoded=json_decode($result, true);
var_dump($decoded);
This is what I get:
array(3) { ["data"]=> array(4)
{
["Chair"]=> array(4)
{ ["id"]=> int(24) ["key"]=> string(5) "Chair" ["name"]=> string(5) "Chair" ["title"]=> string(13) "oak home made" }
["Table"]=> array(4)
{ ["id"]=> int(37) ["key"]=> string(5) "Table" ["name"]=> string(5) "Table" ["title"]=> string(17) "round white table" }
["Closet"]=> array(4)
{ ["id"]=> int(18) ["key"]=> string(6) "Closet" ["name"]=> string(6) "Closet" ["title"]=> string(11) "big and red" }
["Sofa"]=> array(4)
{ ["id"]=> int(110) ["key"]=> string(4) "Sofa" ["name"]=> string(4) "Sofa" ["title"]=> string(21) "room for five persons" }
}
["type"]=> string(9) "furniture" ["version"]=> string(5) "1.1.0"
}
Then I am trying to retrieve "Chair", "Table", "Closet" and "Sofa", but I don't know how to do it. When I try this:
foreach ($decoded as $key => $value) {
echo "key: ".$key;
echo "</br></br>";
echo "value: ".$value;
echo "</br></br>";
return;
}
I get:
key: data
value: Array
Can someone help me get "Chair", "Table", "Closet" and "Sofa", including each of thoses' id, key, name and title?
I have received guides, but they won't help me because I feel like this type of "array" is different then the links for guides I receive.
Thanks!
You are looping through the array on the top most level, while you want to be a level lower than that to be able to loop through all the elements of data, like this:
foreach ($summonerDecoded2['data'] as $key => $value)
{
echo "key: ".$key."</br>";
echo "value id: ".$value['id']."</br>";
echo "value key: ".$value['key']."</br>";
echo "value name: ".$value['name']."</br>";
echo "value title: ".$value['title']."</br>";
}
You can just do this:
$url = 'test.json';
$result=file_get_contents($url);
$decoded = json_decode($result, true);
foreach ( $decoded["data"] as $key => $value) {
echo $value[ "key" ];
echo "<br />";
//You can access data by:
/*
echo $value[ "id" ];
echo $value[ "key" ];
echo $value[ "name" ];
echo $value[ "title" ];
*/
}
This will result to:
Chair
Table
Closet
Sofa

PHP loop through nested JSON to find value

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

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');

Can't get JSON string to parse into an array

I'm using the following PHP code to return a json string:
$itemURL = 'http://***.***.***/search?tag=Football&affiliate_id=&max_results=3';
$response = file_get_contents($itemURL);//curl_exec($curlHandle);
echo $response;
$response = array($response);
echo $response[0];
I get a json string that looks something like this:
[
{
"ID": "123",
"Description": "Champion Football Navy T-shirt",
"HighPrice": 16.99,
"LowPrice": 16.99,
"SalePrice": null,
"OnSale": false,
"URL": "http://www.mystore.com/itemDescription",
"ImageURL": "http://www.mystore.com/mainstore/045.jpg",
"LargeImageURL": "http://www.mystore.com/mainstore/045.jpg",
"ThumbnailImageURL": "http://www.mystore.com/mainstore/045.jpg",
"MiniImageURL": "http://www.mystore.com/mainstore/045.jpg",
"AffiliateID": ""
},
{
"ID": "23",
"Description": "Champion Football Navy T-shirt XL",
"HighPrice": 16.99,
"LowPrice": 16.99,
"SalePrice": null,
"OnSale": false,
"URL": "http://www.mystore.com/itemDescription",
"ImageURL": "http://www.mystore.com/mainstore/045.jpg",
"LargeImageURL": "http://www.mystore.com/mainstore/045.jpg",
"ThumbnailImageURL": "http://www.mystore.com/mainstore/045.jpg",
"MiniImageURL": "http://www.mystore.com/mainstore/045.jpg",
"AffiliateID": ""
}
]
However when I echo $response[0] I get the entire string. If I use json_decode or encode I get a string but with quotes around it. I can't figure out how to cast this dang thing so it operates as an array of objects that I can then iterate through. Thanks for any help in advance
Try this...
$itemURL = 'http://***.***.***/search?tag=Football&affiliate_id=&max_results=3';
$response = file_get_contents($itemURL);//curl_exec($curlHandle);
$response = json_decode($response);
You'll get an object like...
array(2) {
[0]=>
object(stdClass)#1 (12) {
["ID"]=>
string(3) "123"
["Description"]=>
string(30) "Champion Football Navy T-shirt"
["HighPrice"]=>
float(16.99)
["LowPrice"]=>
float(16.99)
["SalePrice"]=>
NULL
["OnSale"]=>
bool(false)
["URL"]=>
string(38) "http://www.mystore.com/itemDescription"
["ImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["LargeImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["ThumbnailImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["MiniImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["AffiliateID"]=>
string(0) ""
}
[1]=>
object(stdClass)#2 (12) {
["ID"]=>
string(2) "23"
["Description"]=>
string(33) "Champion Football Navy T-shirt XL"
["HighPrice"]=>
float(16.99)
["LowPrice"]=>
float(16.99)
["SalePrice"]=>
NULL
["OnSale"]=>
bool(false)
["URL"]=>
string(38) "http://www.mystore.com/itemDescription"
["ImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["LargeImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["ThumbnailImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["MiniImageURL"]=>
string(40) "http://www.mystore.com/mainstore/045.jpg"
["AffiliateID"]=>
string(0) ""
}
}
And then you can access your JSON objects using $response[0], $response[1], etc... Using the specific name of the field like $response[0]->AffiliateID for istance.
you need to call the property you are looking for
IE:
echo response[0].ID; //getting the 1st item in the response array then access the "ID" property of the json object.
The json response is a dynamic object that allows you to interact with all the properties as though you created the object from scratch.
The values inside the [{... and the ... }] are the object values.
so...
var json = '{"ID" : 1, "Prop1" : "Value1", Prop2 : "Value2" }';
can be parsed using jQuery's parseJSON method
var obj= jQuery.parseJSON(json);
echo obj.ID; //1
echo obj.Prop1; //Value
echo obj.Prop2; //Value2
When you have the [... and ...] around the { and } you know this object is an array and needs to be treated accordingly.
Hope this helps.
wm
if (mysql_num_rows($result) > 0) {
$response["events"] = array();
while ($row = mysql_fetch_array($result)) {
$tmparr = array();
$tmparr["uid"] = $row["uid"];
$tmparr["date"] = $row["date"];
$tmparr["hours"] = $row["hours"];
$tmparr["store_name"] = $row["store_name"];
$tmparr["event_information"] = $row["event_information"];
$tmparr["event_type"] = $row["event_type"];
$tmparr["Phone"] = $row["Phone"];
$tmparr["price"] = $row["price"];
$tmparr["address"] = $row["address"];
$tmparr["image_url"] = $row["image_url"];
$tmparr["created_at"] = $row["created_at"];
$tmparr["updated_at"] = $row["updated_at"];
array_push($response["events"], $tmparr);
}
$response["success"] = 1;
echo json_encode($response);
I can't understand what you are trying to do but This is the way that i use in order to return an array of rows of data from a sql query ($result). I hope this helps you

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