Get all values from JSON array - php

Hi would anyone help me how to get all value "clickUrl",
I'm using file_get_content function and i want to wrap it in html
<?php
$json_url = "someone.web.id";
$json = file_get_contents($json_url);
$json=str_replace('},]',"}]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
My Result is
stdClass Object
(
[serialId] => 110153837
[productId] => 212065382
[os] => Linux
[validResponse] => 1
[errorMessage] =>
[adsDetails] => Array
(
[0] => stdClass Object
(
[requestTimestamp] => 1429665317403
[adId] => SAP_272131
[clickUrl] => http://adtrack.king.com
)
[1] => stdClass Object
(
[requestTimestamp] => 1429679659674
[adId] => SAP_182149
[clickUrl] => market://details?id
)
[2] => stdClass Object
(
[requestTimestamp] => 1429679659674
[adId] => SAP_552219
[clickUrl] => http://t.mobitrk.com
)
[3] => stdClass Object
(
[requestTimestamp] => 1429679659674
[adId] => SAP_562515
[clickUrl] => https://app.adjust.io
)
)
)
I dont know why my early posting deleted by meagar

According to your info, you could get an array by:
$clickUrls = array_map(function($val) {
return $val->clickUrl;
}, $data->adsDetails);

Change from stdobject to array and loops around it.
To receive JSON as array, just change this:
$data = json_decode($json);
to This:
$data = json_decode($json,true);
Then, loop around...
foreach ($data['adsDetails'] as $innerArray) {
echo $innerArray['requestTimestamp'].'<br>';
echo $innerArray['adId'].'<br>';
echo $innerArray['clickUrl'].'<br>';
}

Related

Parse JSON from file using PHP from objects/arrays

I get the following output using print_r in php of my decoded JSON:
stdClass Object
(
[assignments] => Array
(
[0] => stdClass Object
(
[assignmentid] => 1
[grades] => Array
(
[0] => stdClass Object
(
[id] => 1
[userid] => 3
[attemptnumber] => 0
[timecreated] => 1484244192
[timemodified] => 1484244203
[grader] => 2
[grade] => 85.00000
)
)
)
)
[warnings] => Array
(
)
)
I want to get the value for [grade] => 85.00000 and store it in a variable. How would I go about doing this?
What about:
$var = $obj->assignments[0]->grades[0]->grade;
Use true as second parameter of json_decode() to decode it to array and then you have to loop over your result.
$data = json_decode($json, true);
foreach ($data['assignments'] as $row) {
foreach ($row['grades'] as $grade) {
echo $grade['grade'];
}
}

Add Array to Existing Object

This seems pretty easy, but I can't figure it out. I have an existing array of objects that was json_decoded. I need to iterate over those objects, append a new array to each, and then put the overall array back together. I can't get the new array to append in the correct place.
function appendToArray($arrayOfObjects) {
$newArray = array();
foreach ($arrayOfObjects as $object) {
echo "<pre>".print_r($object, true)."</pre>";
$newItems = array('item1', 'item2', 'item3');
$moreItems = array('more1', 'more2', 'more3');
$newObject = array();
$newObject["newItems"] = $newItems;
$newObject["moreItems"] = $moreItems;
$rebuiltObject = array();
array_push($rebuiltObject, $object);
$rebuiltObject['new_stuff'] = $newObject;
// $rebuiltObject[0]['new_stuff'] = $newObject;
array_push($newArray, $newObject);
}
return $newArray;
}
Here is an example of one of the objects that I start with (after json_decode of course:
0 => stdClass Object
(
[code] => some code
[first_name] => First
[last_name] => Last
[urls] => stdClass Object
(
[news] => http://www.somesite.com/news
[info] => http://www.somesite.com/info
)
[geo] => stdClass Object
(
[latitude] => 0.0
[longitude] => 0.0
[name] => building name
)
)
When this is done, what I want is this:
0 => stdClass Object
(
[code] => some code
[first_name] => First
[last_name] => Last
[urls] => stdClass Object
(
[news] => http://www.somesite.com/news
[info] => http://www.somesite.com/info
)
[geo] => stdClass Object
(
[latitude] => 0.0
[longitude] => 0.0
[name] => building name
)
[new_stuff] => Array
(
[newItems] => Array
(
[0] => item1
[1] => item2
[2] => item3
)
[moreItems] => Array
(
[0] => more1
[1] => more2
[2] => more3
)
)
)
But what I get is this:
[0] => stdClass Object
(
[code] => some code
[first_name] => First
[last_name] => Last
[urls] => stdClass Object
(
[news] => http://www.somesite.com/news
[info] => http://www.somesite.com/info
)
[geo] => stdClass Object
(
[latitude] => 0.0
[longitude] => 0.0
[name] => building name
)
),
[new_stuff] => Array
(
[newItems] => Array
(
[0] => item1
[1] => item2
[2] => item3
)
[moreItems] => Array
(
[0] => more1
[1] => more2
[2] => more3
)
)
)
Notice how [new_stuff] is outside of the original object. I need to get it inside. Everything else I've tried crashes and I'm totally out of ideas. Can anyone see how I can do this? Thank you!
You solution is one string:
$object->new_stuff = $newObject;
because every $object is object and not array. And adding new property to object is done via -> and not with [].
Full code:
function appendToArray($arrayOfObjects) {
foreach ($arrayOfObjects as $object) {
echo "<pre>".print_r($object, true)."</pre>";
$newItems = array('item1', 'item2', 'item3');
$moreItems = array('more1', 'more2', 'more3');
$newObject = array();
$newObject["newItems"] = $newItems;
$newObject["moreItems"] = $moreItems;
$object->new_stuff = $newObject;
}
return $arrayOfObjects;
}
You can just array_walk and change the object inplace:
array_walk($arrayOfObjects, function(&$item) {
$item->new_stuff = ["newItems" => ['item1', 'item2', 'item3'], etc];
});

Selecting a property from JSON

I have a JSON similar to this one:
{"request":
{"Target":"Affiliate_Offer","Format":"json","Service":"HasOffers","Version":"2","NetworkId":"adattract","Method":"getPayoutDetails","api_key":"bd2e82f029c50b582db85868b7c0b8ab99d095886ab079f87b464bb68486c891","offer_id":"9463"},"response":
{"status":1,"httpStatus":200,"data":{"offer_payout":
{"payout":"0.820"}},"errors":[],"errorMessage":null}}
And I want to select only value of payout which is 0.820.
Here what I try
<?php
include 'db.php';
$result = mysql_query("SELECT * FROM ada WHERE require_approval='0' ORDER BY i2 ASC LIMIT 0,10") or die(mysql_error());
// keeps getting the next row until there are no more to get
while ($row = mysql_fetch_array($result)) {
echo "<div>";
$r = $row['id'];
$ri = $row['i2'];
// $ri contains no. 1 2 3 4 5..//
$json = '';
}
$mydata = json_decode($json, true);
$data = $mydata["response"]["data"];
$pay = $data[$ri]["offer_payout"][payout];
echo "</div>";
mysql_query("INSERT INTO thumb(img,id) VALUES('$nth','$oid')");
echo $pay; //output of 0.8200 but not work plz here i need help//
}
?>
In the vain of 'Give a man a fish and he will feed his family for a day. Teach a man to fish and he will feed his family forever' here is how you find out what a json object looks like.
$json = '{"request":
{"Target":"Affiliate_Offer","Format":"json","Service":"HasOffers","Version":"2","NetworkId":"adattract","Method":"getPayoutDetails","api_key":"bd2e82f029c50b582db85868b7c0b8ab99d095886ab079f87b464bb68486c891","offer_id":"9463"},"response":
{"status":1,"httpStatus":200,"data":{"offer_payout":
{"payout":"0.82000"}},"errors":[],"errorMessage":null}}';
$mydata = json_decode($json,true);
print_r($mydata);
Will output this :-
Array
(
[request] => Array
(
[Target] => Affiliate_Offer
[Format] => json
[Service] => HasOffers
[Version] => 2
[NetworkId] => adattract
[Method] => getPayoutDetails
[api_key] => bd2e82f029c50b582db85868b7c0b8ab99d095886ab079f87b464bb68486c891
[offer_id] => 9463
)
[response] => Array
(
[status] => 1
[httpStatus] => 200
[data] => Array
(
[offer_payout] => Array
(
[payout] => 0.82000
)
)
[errors] => Array
(
)
[errorMessage] =>
)
)
And now you know how to address any and all fields
So the field you want will be
$pay = $mydata["response"]["data"]["offer_payout"]["payout"];
Now you decided to convert a JSON Object to an array, there is no need to do that, and in some ways an object is even easier to address and uses less key strokes than an array.
So leave the ,true out of the json_decode and you get this
$json = '{"request":
{"Target":"Affiliate_Offer","Format":"json","Service":"HasOffers","Version":"2","NetworkId":"adattract","Method":"getPayoutDetails","api_key":"bd2e82f029c50b582db85868b7c0b8ab99d095886ab079f87b464bb68486c891","offer_id":"9463"},"response":
{"status":1,"httpStatus":200,"data":{"offer_payout":
{"payout":"0.82000"}},"errors":[],"errorMessage":null}}';
$mydata = json_decode($json);
print_r($mydata);
Which outputs :-
stdClass Object
(
[request] => stdClass Object
(
[Target] => Affiliate_Offer
[Format] => json
[Service] => HasOffers
[Version] => 2
[NetworkId] => adattract
[Method] => getPayoutDetails
[api_key] => bd2e82f029c50b582db85868b7c0b8ab99d095886ab079f87b464bb68486c891
[offer_id] => 9463
)
[response] => stdClass Object
(
[status] => 1
[httpStatus] => 200
[data] => stdClass Object
(
[offer_payout] => stdClass Object
(
[payout] => 0.82000
)
)
[errors] => Array
(
)
[errorMessage] =>
)
)
Now the field you want to address is :-
$pay = $mydata->response->data->offer_payout->payout;
You can get values from the json as like that:
// your json
$json = '{"request":
{"Target":"Affiliate_Offer","Format":"json","Service":"HasOffers","Version":"2","NetworkId":"adattract","Method":"getPayoutDetails","api_key":"bd2e82f029c50b582db85868b7c0b8ab99d095886ab079f87b464bb68486c891","offer_id":"9463"},"response":
{"status":1,"httpStatus":200,"data":{"offer_payout":
{"payout":"0.82000"}},"errors":[],"errorMessage":null}}';
// json_decode() function with second param true for array format
$json_decoded = json_decode($json,true);
echo $json_decoded['response']['data']['offer_payout']['payout']; //0.82000
How can you get this in your code?
You just need to change these two lines in your code:
$data = $mydata["response"]["data"];
$pay = $data["offer_payout"]['payout']; //0.82000
$pay = $mydata["response"]["data"]["offer_payout"]["payout"];
You might want to cast it to float, as it is a string in the JSON data you provided:
$pay = (float) $mydata["response"]["data"]["offer_payout"]["payout"];
First you need convert json to array
$array =json_decode($json,TRUE); //$json is converted to array
Now you can retrieve any property from the array
The complete code example is
$json = '{"request":
{"Target":"Affiliate_Offer","Format":"json","Service":"HasOffers","Version":"2","NetworkId":"adattract","Method":"getPayoutDetails","api_key":"bd2e82f029c50b582db85868b7c0b8ab99d095886ab079f87b464bb68486c891","offer_id":"9463"},"response":
{"status":1,"httpStatus":200,"data":{"offer_payout":
{"payout":"0.82000"}},"errors":[],"errorMessage":null}}';
$mydata = json_decode($json,true);
print_r($mydata);
OutPut:
Array ( [request] => Array ( [Target] => Affiliate_Offer [Format] => json [Service] => HasOffers [Version] => 2 [NetworkId] => adattract [Method] => getPayoutDetails [api_key] => bd2e82f029c50b582db85868b7c0b8ab99d095886ab079f87b464bb68486c891 [offer_id] => 9463 ) [response] => Array ( [status] => 1 [httpStatus] => 200 [data] => Array ( [offer_payout] => Array ( [payout] => 0.82000 ) ) [errors] => Array ( ) [errorMessage] => ) ) 1
From the result you can retrieve any array property
Eg-
echo $mydata['response']['status'];
OutPut:
1
Hope this will help you.
$mydata = json_decode($json, true);
$data = $mydata['response']['data'];
print_r($data);
print_r($data['offer_payout']['payout']);

Merge arrays in an object

Im new to php and json. can you please suggest me on how to get the my desired output.
JSON File:
{
"1415772360":[
{"apple":"0"},
{"mango":"0"},
{"grapefruit":"0"},
{"melons":"12"},
{"peaches":"2"},
{"banana":"1"}
],
"1415772420":[
{"apple":"0"},
{"mango":"0"},
{"grapefruit":"0"},
{"melons":"7"},
{"peaches":"1"},
{"banana":"1"}
]
}
Desired Output
[
{
"minute":"1415772360",
"apple":"0",
"mango":"0",
"grapefruit":"0",
"melons":"12",
"peaches":"2",
"banana":"1”
},
{
"minute":"1415772420",
"apple:"0",
"mango":"0",
"grapefruit":"0",
"melons":"7",
"peaches":"1",
"banana":"1”
}
]
How can I do this in PHP?
I really appreciate your help. Thanks.
I would give json_decode a try. It won't get your desired output, but it will create an array from your JSON.
Documentation: http://php.net/manual/en/function.json-decode.php
My test:
$json = "{\"1415772360\":[{\"apple\":\"0\"},{\"mango\":\"0\"},{\"grapefruit\":\"0\"},
{\"melons\":\"12\"},{\"peaches\":\"2\"},{\"banana\":\"1\"}], \"1415772420\":
[{\"apple\":\"0\"},{\"mango\":\"0\"},{\"grapefruit\":\"0\"},{\"melons\":\"7\"},
{\"peaches\":\"1\"},{\"banana\":\"1\"}]}";
$new = json_decode($json);
print_r($new);
Output:
stdClass Object ( [1415772360] => Array ( [0] => stdClass Object ( [apple] => 0 )
[1] => stdClass Object ( [mango] => 0 ) [2] => stdClass Object ( [grapefruit] => 0 )
[3] => stdClass Object ( [melons] => 12 ) [4] => stdClass Object ( [peaches] => 2 )
[5] => stdClass Object ( [banana] => 1 ) ) [1415772420] => Array ( [0] => stdClass Object ( [apple] => 0 )
[1] => stdClass Object ( [mango] => 0 ) [2] => stdClass Object ( [grapefruit] => 0 )
[3] => stdClass Object ( [melons] => 7 ) [4] => stdClass Object ( [peaches] => 1 )
[5] => stdClass Object ( [banana] => 1 ) ) )
tyteen4a03 is correct that this just requires some looping to re-write the structure. This would be done as follows:
// Original JSON string
$json = '{
"1415772360":[
{"apple":"0"},
{"mango":"0"},
{"grapefruit":"0"},
{"melons":"12"},
{"peaches":"2"},
{"banana":"1"}
],
"1415772420":[
{"apple":"0"},
{"mango":"0"},
{"grapefruit":"0"},
{"melons":"7"},
{"peaches":"1"},
{"banana":"1"}
]
}';
// Convert JSON to array
$content = json_decode($json);
// Create new array container
$crate = array();
// Get minutes
foreach ($content AS $minute => $fruitbasket) {
$tmp = new stdClass;
$tmp->minutes = $minute;
// Get array of objects
foreach ($fruitbasket AS $fruits)
{
// Get object element and value
foreach ($fruits AS $key => $value)
{
// add to temporary object
$tmp->$key = $value;
}
}
// write to new array
$crate[] = $tmp;
}
print(json_encode($crate));

How to iterate through a nested stdClass? [duplicate]

This question already has answers here:
stdClass object and foreach loops
(5 answers)
Closed 4 months ago.
I have an object like this:
stdClass Object
(
[_count] => 10
[_start] => 0
[_total] => 37
[values] => Array
(
[0] => stdClass Object
(
[_key] => 50180
[group] => stdClass Object
(
[id] => 50180
[name] => CriticalChain
)
)
[1] => stdClass Object
(
[_key] => 2357895
[group] => stdClass Object
(
[id] => 2357895
[name] => Data Modeling
)
)
[2] => stdClass Object
(
[_key] => 1992105
[group] => stdClass Object
(
[id] => 1992105
[name] => SQL Server Users in Israel
)
)
[3] => stdClass Object
(
[_key] => 37988
[group] => stdClass Object
(
[id] => 37988
[name] => CDO/CIO/CTO Leadership Council
)
)
[4] => stdClass Object
(
[_key] => 4024801
[group] => stdClass Object
(
[id] => 4024801
[name] => BiT-HR, BI & IT Placement Agency
)
)
[5] => stdClass Object
(
[_key] => 37845
[group] => stdClass Object
(
[id] => 37845
[name] => Israel Technology Group
)
)
[6] => stdClass Object
(
[_key] => 51464
[group] => stdClass Object
(
[id] => 51464
[name] => Israel DBA's
)
)
[7] => stdClass Object
(
[_key] => 66097
[group] => stdClass Object
(
[id] => 66097
[name] => SQLDBA
)
)
[8] => stdClass Object
(
[_key] => 4462353
[group] => stdClass Object
(
[id] => 4462353
[name] => Israel High-Tech Group
)
)
[9] => stdClass Object
(
[_key] => 4203807
[group] => stdClass Object
(
[id] => 4203807
[name] => Microsoft Team Foundation Server
)
)
)
)
I need to get the id and name in an HTML table, but I seem to have a hard time iterating through this object. TIA. I understand that I need to get to the Values Array, and then to the group object, but I trip over the transitions between object and array and foreach vs index based iteration.
For example I tried this:
foreach ($res as $values) { print "\n"; print_r ($values); }
It iterates trough the object, but it also gives me useless
10 0 37
echo "<table>"
foreach ($object->values as $arr) {
foreach ($arr as $obj) {
$id = $obj->group->id;
$name = $obj->group->name;
$html = "<tr>";
$html .= "<td>Name : $name</td>";
$html .= "<td>Id : $id</td>";
$html .= "</tr>";
}
}
echo "</table>";
Since this is the top result in Google if you search for iterate over stdclass it may be helpful to answer the question in the title:
You can iterate overa stdclass simply by using foreach:
$user = new \stdClass();
$user->flag = 'red';
foreach ($user as $key => $value) {
// $key is `flag`
// $value is `red`
}
function objectToArray( $data )
{
if ( is_object( $data ) )
$d = get_object_vars( $data );
}
Convert the Object to array first like:
$results = objectToArray( $results );
and use
foreach( $results as result ){... ...}
I know it's an old post , but for sake of others:
when working with stdClass you should use Reflections:
$obj = new ReflectionObject($object);
$propeties = $obj->getProperties();
foreach($properties as $property) {
$name = $property->getName(); <-- this is the reflection class
$value = $object->$name; <--- $object is your original $object
here you need to handle the result (store in array etc)
}
foreach($res->values as $value) {
print_r($value);
}

Categories