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 ?

有帮助吗?

解决方案 2

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

其他提示

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
}
$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'];
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top