Reputation: 4336
My code is as follows
$results = array();
$results[] = json_decode("json api response url", true);
$results[] = json_decode("json api response url 2", true);
$results[] = json_decode("json api response url 3", true);
foreach($results as $result) {
$decoded = $result['Info'];
usort($decoded, function($a, $b) { return $a['price'] > $b['price'] ? 1 : -1; });
foreach($decoded as $row) {
echo $row['price'];
}
}
JSON array is returned as follows
["Info"]=>
[0]=>
array(13) {
["price"]=>
int(3000)
}
[1]=>
array(13) {
["price"]=>
int(5000)
it's doing a usort
for every json_decode
reponse instead of all of them together, is their a way around this or not ?
Upvotes: 0
Views: 2355
Reputation: 2835
You are performing a usort on every item inside the array. Try to do the usort before you loop over the results. I have no idea if this will work, but it should point you to the right direction.
$results = array();
$results[] = json_decode("json api response url", true);
$results[] = json_decode("json api response url 2", true);
$results[] = json_decode("json api response url 3", true);
usort($results, function($a, $b) {
return $a['Info']['price'] > $b['Info']['price'] ? 1 : -1;
});
foreach($results as $result) {
// do your looped stuff
}
Upvotes: 2
Reputation: 6909
I think what you want to do, is to concatenate all of the JSON responses and put them together, instead of creating 3 different array elements in results[]; Look into array_merge():
$result = array();
$arr1 = json_decode("json api response url", true);
$arr2 = json_decode("json api response url 2", true);
$arr3 = json_decode("json api response url 3", true);
$result = array_merge($arr1['Info'], $arr2['Info'], $arr3['Info']);
$decoded = $result;
usort($decoded, function($a, $b) { return $a['price'] > $b['price'] ? 1 : -1; });
foreach($decoded as $row) {
echo $row['price'];
}
Upvotes: 1
Reputation: 16307
$results = array();
$results[] = json_decode("json api response url", true);
$results[] = json_decode("json api response url 2", true);
$results[] = json_decode("json api response url 3", true);
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
usort($results, "cmp");
foreach($results as $row) {
echo $row['price'];
}
Upvotes: 0