Eem*_*Jee 0 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"]=>
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"
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我如何根据 的值对其结果进行排序col_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"
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试过asort()在这里使用,但它似乎只支持关联数组。有什么办法可以解决这个问题吗?
您可以使用usort()
$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);
Run Code Online (Sandbox Code Playgroud)
输出 :
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)
Run Code Online (Sandbox Code Playgroud)
但我建议您直接从 SQL 查询中对结果进行排序:
SELECT *
FROM yourTable
...
ORDER BY col_order ASC
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21125 次 |
| 最近记录: |