我需要将数组重组为自定义顺序

时间:2014-11-03 15:51:36

标签: php arrays

我有一个多维数据数组,我需要对它进行排序以匹配我所拥有的特定顺序。 我有以下数组:

原始阵列:

$orig_array = array(
    'Grapes' => array("one", "two", "three"),
    'Apples' => array("one", "two", "three"),
    'Oranges' => array("one", "two", "three"),
    'Pears' => array("one", "two", "three"),
    'Watermelon' => array("one", "two", "three"),
    'Banana' => array("one", "two", "three")
);

预期数组顺序:

$order = array(
    "Apples",
    "Watermelon",
    "Grapes",
    "Banana",
    "Pears",
    "Oranges"
);

我尝试了什么:

usort($orig_array, function ($a, $b) use ($order) {
    $pos_a = array_search($a, $order);
    $pos_b = array_search($b, $order);
     return 0;
});

var_dump($orig_array);

但我没有结果。有人可以指导我理解如何使用这个功能,以便我可以得到预期的结果?我非常感谢你的帮助。

1 个答案:

答案 0 :(得分:3)

如果我理解,您有一个$order数组,确定数组顺序的因素,并且您希望根据此$orig_array数组重新组织$order

我的回答:

$orig_array = array(
    'Grapes' => array("one", "two", "three"),
    'Apples' => array("one", "two", "three"),
    'Oranges' => array("one", "two", "three"),
    'Pears' => array("one", "two", "three"),
    'Watermelon' => array("one", "two", "three"),
    'Banana' => array("one", "two", "three")
);

$order = array(
    "Apples",
    "Watermelon",
    "Grapes",
    "Banana",
    "Pears",
    "Oranges"
);

foreach ($order as $key) {

    $new_array[$key] = $orig_array[$key];
}

var_dump($new_array);

输出是:

array
  'Apples' => 
    array
      0 => string 'one' (length=3)
      1 => string 'two' (length=3)
      2 => string 'three' (length=5)
  'Watermelon' => 
    array
      0 => string 'one' (length=3)
      1 => string 'two' (length=3)
      2 => string 'three' (length=5)
  'Grapes' => 
    array
      0 => string 'one' (length=3)
      1 => string 'two' (length=3)
      2 => string 'three' (length=5)
  'Banana' => 
    array
      0 => string 'one' (length=3)
      1 => string 'two' (length=3)
      2 => string 'three' (length=5)
  'Pears' => 
    array
      0 => string 'one' (length=3)
      1 => string 'two' (length=3)
      2 => string 'three' (length=5)
  'Oranges' => 
    array
      0 => string 'one' (length=3)
      1 => string 'two' (length=3)
      2 => string 'three' (length=5)

编辑:正如Amal Mulari在我的回答评论中所说:

$new_array = array_combine($order, $orig_array); 
var_dump($new_array);
//More elegant, 1 line solution.

注意:如果数组的元素相同,此解决方案仅有效!如果不相同,例如'Apples' => array ("two", "three"); and 'Melone' => array('four', 'five');此解决方案无法按预期工作!