如何在PHP中按值对对象数组集合排序
所以我从数据库中得到了这个结果:如何在PHP中按值对对象数组集合排序,php,arrays,sorting,arraycollection,Php,Arrays,Sorting,Arraycollection,所以我从数据库中得到了这个结果: object(Illuminate\Support\Collection)#538 (1) { ["items":protected]=> array(3) { [0]=> object(stdClass)#536 (3) { ["col_header"]=> string(7) "other_1" ["col_order"]=>
object(Illuminate\Support\Collection)#538 (1) {
["items":protected]=>
array(3) {
[0]=>
object(stdClass)#536 (3) {
["col_header"]=>
string(7) "other_1"
["col_order"]=>
int(12)
["data"]=>
string(13) "asdgasdgfasdg"
}
[1]=>
object(stdClass)#545 (3) {
["col_header"]=>
string(7) "other_2"
["col_order"]=>
int(10)
["data"]=>
string(10) "dfhgsdhgsd"
}
[2]=>
object(stdClass)#533 (3) {
["col_header"]=>
string(7) "other_3"
["col_order"]=>
int(11)
["data"]=>
string(1) "s"
}
}
现在,如何根据col\u order
的值对其结果进行排序?结果如下:
object(Illuminate\Support\Collection)#538 (1) {
["items":protected]=>
array(3) {
[0]=>
object(stdClass)#545 (3) {
["col_header"]=>
string(7) "other_2"
["col_order"]=>
int(10)
["data"]=>
string(10) "dfhgsdhgsd"
}
[1]=>
object(stdClass)#533 (3) {
["col_header"]=>
string(7) "other_3"
["col_order"]=>
int(11)
["data"]=>
string(1) "s"
}
[2]=>
object(stdClass)#536 (3) {
["col_header"]=>
string(7) "other_1"
["col_order"]=>
int(12)
["data"]=>
string(13) "asdgasdgfasdg"
}
}
我尝试在这里使用asort()
,但它似乎只支持关联数组。有什么方法可以把这个排序出来吗?答案是-它通过用户定义的比较函数进行排序。将以下代码段中的a
替换为col\u顺序
:
<?php
$class1 = new stdClass();
$class1->a = 1;
$class2 = new stdClass();
$class2->a = 2;
$class3 = new stdClass();
$class3->a = 3;
$input = [$class3,$class2,$class1];
var_dump($input);
usort($input, function($a, $b) {
if ($a->a == $b->a) {
return 0;
}
return ($a->a < $b->a) ? -1 : 1;
});
var_dump($input);
您可以使用
但我建议您直接从SQL查询对结果进行排序:
SELECT *
FROM yourTable
...
ORDER BY col_order ASC
您想知道为什么不在查询中使用orderBy吗?因为我以为你在使用laravel elquent,所以你可以在你的电脑上使用orderBy(“col_order”)query@MD.JubairMizan谢谢你的邀请。我还没想到呢!它解决了我的问题,将在我未来的场景中使用答案,函数体可以是php7中带有spaceship操作符的一行:return$a->a$b->a代码>@FilipHalaxa谢谢,我会把它添加到我的答案中。
$test = array(array("col_header" => "other_1",
"col_order" => 12,
"data" => "asdgasdgfasdg"),
array("col_header" => "other_2",
"col_order" => 10,
"data" => "dfhgsdhgsd"),
array("col_header" => "other_3",
"col_order" => 11,
"data" => "s"));
usort($test, function($a, $b)
{
if ($a["col_order"] == $b["col_order"])
return (0);
return (($a["col_order"] < $b["col_order"]) ? -1 : 1);
});
var_dump($test);
array (size=3)
0 =>
array (size=3)
'col_header' => string 'other_2' (length=7)
'col_order' => int 10
'data' => string 'dfhgsdhgsd' (length=10)
1 =>
array (size=3)
'col_header' => string 'other_3' (length=7)
'col_order' => int 11
'data' => string 's' (length=1)
2 =>
array (size=3)
'col_header' => string 'other_1' (length=7)
'col_order' => int 12
'data' => string 'asdgasdgfasdg' (length=13)
SELECT *
FROM yourTable
...
ORDER BY col_order ASC