PHP 按值对 cURL 响应数组进行数字排序

PHP sort cURL response array numerically by value

提问人:Joey Martin 提问时间:6/30/2022 更新时间:6/30/2022 访问量:156

问:

我有一个卷曲响应,它给了我几行结果。 我需要能够按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;
}


如果我删除 usort,我的代码就可以完美运行。我只需要排序即可工作。 我希望看到 25 行结果,按total_views排序。 我已经看过 usort,但我只是无法弄清楚它需要去哪里——或者这甚至是最好的方法。

PHP 数组排序 curl usort

评论

1赞 CBroe 6/30/2022
这回答了你的问题吗?如何在PHP中对数组和数据进行排序?

答:

1赞 aynber 6/30/2022 #1

你用array_column让它有点太复杂了。将其更改为仅获取所需的数组键,它将对数据进行排序:

$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,
 ],
]

*/

评论

0赞 Joey Martin 6/30/2022
如果查看返回的数组,则返回以 DATA 开头。那么它会是 usort($data, function($a, $b) { $a = $a['data']['total_visits']; $b = $b['data']['total_visits']; return ($a < $b) ? -1 : 1; });我试过了,但没有用。
2赞 IMSoP 6/30/2022
@JoeyMartin “data”键位于您正在排序的整个项目列表周围,而不是在正在比较的单个元素中。所以你想要usort($data['data'], ...
1赞 IMSoP 6/30/2022
请注意,可以使用“宇宙飞船运算符”进行简化: 如果您跳过额外的赋值,也可以将整个回调函数简化为单个表达式箭头函数:return ($a < $b) ? -1 : 1;return $a <=> $b;usort($data, fn($a,$b) => $a['total_visits'] <=> $b['total_visits']);