Selecting a property from JSON - php

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

Related

Get data from inside array in Php

With using of query i am getting result in array, i want to get this data in one array,
I am getting result like following way
Array
(
[0] => stdClass Object
(
[id] => 2
[full_name] => amit sharma
)
[1] => stdClass Object
(
[id] => 1
[full_name] => amit
)
)
I tried with following code but not working for me,Where i am wrong,Here is my code
$sql = "//select query";
$result= $this->db->query($sql)->result();
$total=count($result);
if($total>0)
{
$data=array();
foreach($result as $records)
{
$data[]=$records;
}
echo "<pre>";print_R($data);
}
You can easily loop it and get the values in array as below.
$post_id = array((object) (array(
'id' => 1,
'full_name' => "Amit Sharma",
)), (object) (array(
'id' => 2,
'full_name' => "Amit",
)), (object) (array(
'id' => 3,
'full_name' => "Amit Rohan",
)));
foreach ($post_id as $key => $value)
{ $result[] = array("id"=>$value->id, "full_name"=>$value->full_name); }
echo "<pre>";print_r($result);
Simply use json_encode() and json_decode()
I have created same object as of your example, just ignore the code upto:
$result = [$objOne, $objTwo];
Use your $result
Json encode and decode it to get an associative array in return.
Code:
<?php
$objOne = new stdClass();
$objOne->id = 2;
$objOne->full_name = 'amit sharma';
$objTwo = new stdClass();
$objTwo->id = 1;
$objTwo->full_name = 'amit';
$result = [$objOne, $objTwo];
$arr = json_decode(json_encode($result), TRUE);
echo '<pre>';
print_r($result);
echo '</pre>';
echo '<pre>';
print_r($arr);
echo '</pre>';
?>
Output:
Array
(
[0] => stdClass Object
(
[id] => 2
[full_name] => amit sharma
)
[1] => stdClass Object
(
[id] => 1
[full_name] => amit
)
)
Array
(
[0] => Array
(
[id] => 2
[full_name] => amit sharma
)
[1] => Array
(
[id] => 1
[full_name] => amit
)
)

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'];
}
}

Get all values from JSON array

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

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

Getting an objects property with slashes in it

I'm getting a json result back from an api request to the freebase database.
This is part of the object returned called $json. A var dump of $json:
stdClass Object
(
[name] => Abomey
[/location/statistical_region/population_growth_rate] =>
[/common/topic/article] => Array
(
[0] => stdClass Object
(
[id] => /m/0jk2c
)
)
How can I subtract the /m/0jk2c part?
$json->/common/topic/article[0]->id (obviously) doesn't work.
This should do it:
$json->{"/common/topic/article"}[0]->id
This is what you should use
$class->{'/location/statistical_region/population_growth_rate'}['/common/topic/article'][0]->id
Reason your Object looks like this
$std = new stdClass();
$std->id = '/m/0jk2c' ;
$json = new stdClass();
$json->name = "Abomey" ;
$json->{'/location/statistical_region/population_growth_rate'} = array('/common/topic/article'=>array($std));
If you run
var_dump($json->{'/location/statistical_region/population_growth_rate'}['/common/topic/article'][0]->id);
Output
string '/m/0jk2c' (length=8)
Run
echo "<pre>";
print_r($json);
Output
stdClass Object
(
[name] => Abomey
[/location/statistical_region/population_growth_rate] => Array
(
[/common/topic/article] => Array
(
[0] => stdClass Object
(
[id] => /m/0jk2c
)
)
)
)

Categories