按特定顺序按多个键对数组进行排序

时间:2013-01-25 09:41:01

标签: php sorting

我想按以下顺序按多个键对以下数组进行排序:首先是“type”,然后是“product”,最后是“name”。虽然我的客户希望“产品”按特定顺序排序,但很容易用usort完成:Stapler,Binder,Book。

$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' => '...'
    )
);

有谁知道一个聪明的方法来实现这个目标?

2 个答案:

答案 0 :(得分:1)

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']]

答案 1 :(得分:1)

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']);
});
相关问题