如何重新排序多维数组?

时间:2017-01-01 19:23:16

标签: php arrays multidimensional-array transform

假设我有以下数组:

Array
(
    [0] => Array
        (
            [0] => 1200
            [1] => 2541
            [2] => 2540
            [3] => 2539
        )
    [1] => Array
        (
            [0] => Television
            [1] => Monitor
            [2] => Car
            [3] => Bike
        )
    [2] => Array
        (
            [0] => Electrodomestic
            [1] => Computer Stuff
            [2] => Vehicle
            [3] => Vehicle
        )
)

我想单独安排,如下:

Array
(
    [0] => Array
        (
            [0] => 1200
            [1] => Television
            [2] => Electrodomestic
        )
    [1] => Array
        (
            [0] => 2541
            [1] => Monitor
            [2] => Computer Stuff
        )
    [2] => Array
        (
            [0] => 2540
            [1] => Car
            [2] => Vehicle
        )
    [3] => Array
        (
            [0] => 2539
            [1] => Bike
            [2] => Vehicle
        )
)

我该怎么做?

我想将我的简单数组(从我从REGEX中提取的数据)重新加载到包含我的个人"对象"的数组中。

1 个答案:

答案 0 :(得分:1)

无所事事,所以这是一个可能的解决方案:

$a = Array
(
    '0' => Array
        (
            '0' => 1200,
            '1' => 2541,
            '2' => 2540,
            '3' => 2539,
        ),
    '1' => Array
        (
            '0' => 'Television',
            '1' => 'Monitor',
            '2' => 'Car',
            '3' => 'Bike',
        ),
    '2' => Array
        (
            '0' => 'Electrodomestic',
            '1' => 'Computer Stuff',
            '2' => 'Vehicle',
            '3' => 'Vehicle',
        )
);

// take a size of every subarray
$t = sizeof($a[0]);
// do a loop
$new_a = [];
for($i =0; $i < $t; $i ++) {
    // `array_column` extracts every value 
    // with key `$i` from each element of 
    // `$a` array and adds these values
    // to a new array
    $new_a[] = array_column($a, $i);
}

echo'<pre>',print_r($new_a),'</pre>';

警告array_column中引入了php5.5