Home > Software design >  PHP sort cURL response array numerically by value
PHP sort cURL response array numerically by value

Time:07-15

I have a curl response that gives me several lines of results. I need to be able to sort by the value given in total_views.


results from print_r($data);

[data] => Array ( 
[0] => Array ( [total_visits] => 31021 [total_views] => 26674 )
[1] => Array ( [total_visits] => 24077 [total_views] => 5567 )
[2] => Array ( [total_visits] => 11111 [total_views] => 15538 )
[3] => Array ( [total_visits] => 22222 [total_views] => 5435 )
)


$data = json_decode($result,true);
print_r($data);

///me trying to use usort///
usort($data, function($a, $b) {
    $a = array_column($a[0], 'total_visits');
    $b = array_column($b[0], 'total_visits');
    return ($a < $b) ? -1 : 1;
});

$i=1;
foreach ($data['data'] as $val)
{
//only loop 25 times
if ($i   > 25) break;

$totalviews=$val['total_views'];
$totalvisits=$val['total_visits'];

echo $totalviews." ".$totalvisits;
}


If i remove the usort, my code works perfect. I just need the sorting to work. I expect to see 25 lines of results, sorted by total_views. I have looked at usort but I just can't figure out exactly where it needs to go - or that's even the best way to do this.

CodePudding user response:

You're making it slightly too complicated with the array_column. Change that to just getting the array key you want, and it will sort the data:

$data = array(
    0 => array('total_visits' => 31021, 'total_views' => 26674),
    1 => array('total_visits' => 24077, 'total_views' => 5567),
    2 => array('total_visits' => 11111, 'total_views' => 15538),
    3 => array('total_visits' => 22222, 'total_views' => 5435),
);


///me trying to use usort///
usort($data, function($a, $b) {
    $a = $a['total_visits'];
    $b = $b['total_visits'];
    return ($a < $b) ? -1 : 1;
});

/*
[
 [
   "total_visits" => 11111,
   "total_views" => 15538,
 ],
 [
   "total_visits" => 22222,
   "total_views" => 5435,
 ],
 [
   "total_visits" => 24077,
   "total_views" => 5567,
 ],
 [
   "total_visits" => 31021,
   "total_views" => 26674,
 ],
]

*/
  • Related