重新排序多维数组

时间:2014-03-30 06:01:40

标签: php arrays multidimensional-array

我遇到过这样的问题:使用PHP重新排序此数组的最佳方法是什么:

Array { 
      Array[0]
      (
        [car_1] => 'Toyota',
        [car_2] => 'Camry',
        [car_3] => 'Mazda',
      ),
     Array[1]
      (
        [car_1] => 'Mustang',
        [car_2] => 'Camry',
        [car_3] => 'Dodge',
        [car_4] => 'Ram',

      ),
    Array[2]
      (
        [car_1] => 'Mustang',
        [car_2] => 'Camry',
        [car_3] => 'Eclipse',
        [car_4] => 'Acura',
       )
}

最终的解决方案应该是:

 Array ( 
        [car_1] => 'Toyota',
        [car_2] => 'Camry',
        [car_3] => 'Mazda',
        [car_4] => 'Mustang', 
        [car_5] => 'Dodge',
        [car_6] => 'Ram',
        [car_7] => 'Eclipse',
        [car_8] => 'Acura',

       )

我不确定如何重新排序数组索引,就像它们在结果中实现的那样:

function array_reorder($arry)
{ 
    $reordered_arry = array();
    $size = sizeof($arry);        //the outer loop:
    for($i=0;$i<$size;$i++){
        if($i == 0){
            array_push($reordered_arry,array_filter($arry[$i]));
        }
        else{
            //the inner array loop

            foreach(array_filter($arry[$i]) as $key_outer =>$value_outer){ 
                print_r($arry[$i]);
                foreach($reordered_arry[0] as $key=>$value){
                    //print_r('value outer is'.$value_outer.'value inner is:'.$value.'<br>');
                    //print_r($reordered_arry[0]);
                    if($value_outer == $value) { 
                        unset($reordered_arry[0][$key]);
                    }else {
                        // array_push($reordered_arry,$value_outer);
                    } 
                }
            }
            return $reordered_arry;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

使用RecursiveArrayIterator课程。

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$new_arr = array();$i=1;
foreach($it as $v) {
    if(!in_array($v,$new_arr))
    {
    $new_arr['car_'.$i]=$v;
    $i++;
    }
}
print_r($new_arr);

<强> OUTPUT :

Array
(
    [car_1] => Toyota
    [car_2] => Camry
    [car_3] => Mazda
    [car_4] => Mustang
    [car_5] => Dodge
    [car_6] => Ram
    [car_7] => Eclipse
    [car_8] => Acura
)

Working Demo