我想按以下顺序按多个键对以下数组进行排序:首先按"type“排序,然后按"product”排序,最后按"name“排序。使用usort很容易做到这一点,尽管我的客户希望“产品”按特定的顺序排序:装订器、装订器、书籍。
$arr = array(
array(
'type' => 'School',
'product' => 'Book',
'name' => 'My book',
'data' => '...'
),
array(
'type' => 'Job',
'product' => 'Stapler',
'name' => 'My stapler',
'data' => '...'
),
array(
'type' => 'Personal',
'product' => 'Binder',
'name' => 'My binder',
'data' => '...'
),
array(
'type' => 'School',
'product' => 'Book',
'name' => 'My book',
'data' => '...'
)
);有没有人知道一个聪明的方法来实现这一点?
发布于 2013-01-25 17:48:17
usort($arr, function ($a, $b) {
// by type
$r = strcmp($a['type'], $b['type']);
if ($r !== 0) {
return $r;
}
// by product
// note: one might want to check if `$a/$b['product']` really is in `$order`
$order = array('Stapler', 'Binder', 'Book');
$r = array_search($a['product'], $order) - array_search($b['product'], $order);
if ($r !== 0) {
return $r;
}
// or similar, with a little help by @fab ;)
/*
$order = array('Stapler' => 0, 'Binder' => 1, 'Book' => 2);
$r = $order[$a['product']] - $order[$b['product']];
if ($r !== 0) {
return $r;
}
*/
// name
return strcmp($a['name'], $b['name']);
});发布于 2013-01-25 17:48:02
usort不会限制您这样做。我假设您的问题是如何比较排序回调函数中的product值。这可以使用地图来完成,例如:
$mapProductOrder = array_flip(array('Stapler', 'Binder', 'Book'));
// same as: array('Stapler' => 0, 'Binder' => 1, 'Book' => 2)要比较$item1和$item2的用法:
$mapProductOrder[$item1['product']] < $mapProductOrder[$item2['product']]https://stackoverflow.com/questions/14519068
复制相似问题