John Davidson

PHP sort cURL response array numerically by value

0 comments
Message:


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.



My Answer:
Array
(
[0] => Array
(
[title] => Title 1
[total_views] => 100
)

[1] => Array
(
[title] => Title 2
[total_views] => 50
)

[2] => Array
(
[title] => Title 3
[total_views] => 200
)
)

To sort the array numerically by the value of total_views, you can use the usort function in PHP. Here's an example code snippet to achieve this:

php
usort($data, function($a, $b) {
return $a['total_views'] - $b['total_views'];
});

print_r($data);


This code will sort the $data array in ascending order based on the total_views value. If you want to sort in descending order, you can change the comparison in the usort function to $b['total_views'] - $a['total_views'].

Rate this post

4 of 5 based on 1320 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us