PHP自定义重组数组

时间:2014-06-02 09:57:55

标签: php arrays

我想重新组合数组,但我对列和分组子数组有问题:
我的数组:

[0] => Array
(
    [0] => 1393/03
    [1] => 5666562
    [2] => 5
)

[1] => Array
    (
        [0] => 1393/03
        [1] => 491380
        [2] => 6
    )

[2] => Array
    (
        [0] => 1393/03
        [1] => 4210423
        [2] => 30
    )

[3] => Array
    (
        [0] => 1393/03
        [1] => 351000
        [2] => 55
    )

[4] => Array
    (
        [0] => 1393/03
        [1] => 53000
        [2] => 60
    )

[5] => Array
    (
        [0] => 1393/02
        [1] => 15799573
        [2] => 5
    )

[6] => Array
    (
        [0] => 1393/02
        [1] => 1144313
        [2] => 6
    )

[7] => Array
    (
        [0] => 1393/02
        [1] => 12131004
        [2] => 30
    )

[8] => Array
    (
        [0] => 1393/02
        [1] => 39000
        [2] => 55
    )

结果:(必须如此:)

[0] => Array
    (
        [Date] => 1393/03
        [5] => 5666562
        [6] => 491380
        [30] => 4210423
        [60] => 53000
    )

[1] => Array
    (
        [Date] => 1393/02
        [5] => 15799573
        [6] => 1144313
        [30] => 12131004
        [60] => 39000
    )

我尝试用foreach arrays自己做,并参考互联网上的样本和堆栈溢出,但我找不到一个好的解决方案。

1 个答案:

答案 0 :(得分:1)

简单的foreach循环应该足够了。考虑这个例子:

$new_values = array();
$values = array( array('1393/03', 5666562, 5), array('1393/03', 491380, 6), array('1393/03', 4210423, 30), array('1393/03', 351000, 55), array('1393/03', 53000, 60), array('1393/02', 15799573, 5), array('1393/02', 1144313, 6), array('1393/02', 12131004, 30), array('1393/02', 39000, 55),);

foreach($values as $key => $value) {
    $new_values[$value[0]]['Date'] = $value[0];
    $new_values[$value[0]][$value[2]] = $value[1];
}

$new_values = array_values($new_values);

echo "<pre>";
print_r($new_values);
echo "</pre>";

Sample Output