gpt4 book ai didi

php - 如何在 PHP 中按字段值数组对数组进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:28:54 27 4
gpt4 key购买 nike

我想按特定值对数据集合进行排序,例如在 sql ORDER BY VALUES() 中,但在 PHP 中。我有这样的数组

$array = array(
array('name' => 'Milk', 'type' => 'drink'),
array('name' => 'Coffee', 'type' => 'drink'),
array('name' => 'Orange', 'type' => 'fruit'),
array('name' => 'Computer', 'type' => 'other'),
array('name' => 'Water', 'type' => 'other'),
);

我想按类型而不是按字母顺序排序数据,而是按我指定的特定值排序,按 other 类型排序,然后是 drink,然后是 fruit 。所以结果应该是:

 $array = array(
array('name' => 'Computer', 'type' => 'other'),
array('name' => 'Water', 'type' => 'other'),
array('name' => 'Milk', 'type' => 'drink'),
array('name' => 'Coffee', 'type' => 'drink'),
array('name' => 'Orange', 'type' => 'fruit'),
);

我试过 usort 但我不知道如何比较 2 个值来实现它。谢谢。

最佳答案

你也可以这样试试,

$array = array(
array('name' => 'Milk', 'type' => 'drink'),
array('name' => 'Coffee', 'type' => 'drink'),
array('name' => 'Orange', 'type' => 'fruit'),
array('name' => 'Computer', 'type' => 'other'),
array('name' => 'Water', 'type' => 'other'),
);

// array_flip turns 0 => 'other', 1 => 'drink', ... into 'other' => 0, 'drink' => 1, ...
$order=array_flip(array('other','drink','fruit'));

usort($array, function($x, $y) use($order) {
if (!isset($order[$x['type']], $order[$y['type']])) {
// none of the ids have order, so sort by bare type
return $x['type'] - $y['type'];
}
else if (!isset($order[$x['type']])) {
// x does not have order, put it last
return 1;
}
else if (!isset($order[$y['type']])) {
// y does not have order, put it last
return -1;
}

// both have types, use them
return $order[$x['type']] - $order[$y['type']];
});

echo "<pre>";
print_r($array);

输出:-数组

(
[0] => Array
(
[name] => Computer
[type] => other
)

[1] => Array
(
[name] => Water
[type] => other
)

[2] => Array
(
[name] => Milk
[type] => drink
)

[3] => Array
(
[name] => Coffee
[type] => drink
)

[4] => Array
(
[name] => Orange
[type] => fruit
)

)

关于php - 如何在 PHP 中按字段值数组对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49164849/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com