1

我正在尝试按键组合数组。所以所有以相同子键开头的子数组都会合并为一个子数组。另外,我想保留匹配值的最小值。

目前这就是我所拥有的:

$statement = Array
(
    [662_0] => Array
        (
            [0] => 06-01-2012
            [1] => 436
            [2] => MEDIA
            [3] => 2006
            [4] => Template Testing
            [5] => KS
            [6] => 662
            [7] => 0
            [8] => 0
            [9] => 0
            [10] => 0
            [11] => 0
            [12] => 1290
            [13] => 1290.00
            [14] => 0.00
            [15] => 0
            [16] => 1290.00
        )

    [662_1] => Array
        (
            [0] => 06-01-2012
            [1] => 436
            [2] => MEDIA
            [3] => 2006
            [4] => Template Testing
            [5] => KS
            [6] => 662
            [7] => 295.00
            [8] => 0
            [9] => 0
            [10] => 0
            [11] => 0
            [12] => 995
            [13] => 1290.00
            [14] => 0.00
            [15] => 0
            [16] => 1290.00
        )

    [662_2] => Array
        (
            [0] => 06-01-2012
            [1] => 436
            [2] => MEDIA
            [3] => 2006
            [4] => Template Testing
            [5] => KS
            [6] => 662
            [7] => 0
            [8] => 0
            [9] => 0
            [10] => 0
            [11] => 0
            [12] => 1290
            [13] => 1290.00
            [14] => 0.00
            [15] => 0
            [16] => 1290.00
        )

    [663_0] => Array
        (
            blah blah blah...
        )
);

这就是我想要的:

$statement = Array
(
    [662] => Array
        (
            [0] => 06-01-2012
            [1] => 436
            [2] => MEDIA
            [3] => 2006
            [4] => Template Testing
            [5] => KS
            [6] => 662
            [7] => 295.00
            [8] => 0
            [9] => 0
            [10] => 0
            [11] => 0
            [12] => 995
            [13] => 1290.00
            [14] => 0.00
            [15] => 0
            [16] => 1290.00
        )

    [663] => Array
        (
            blah blah blah...
        )
);

如果需要,很高兴提供更多信息!谢谢!!!

4

1 回答 1

0

此代码遍历您的原始数组,切入_以获得项目的组合标识符并将它们合并在一起,如果新值小于已设置的值,则替换结果数组中的值。

<?php
$original = array(
        '122_0' => array('k1'=>4, 'k2'=>2),
        '122_1' => array('k2'=>3, 'k3'=>3),
        '122_2' => array('k3'=>2, 'k4'=>4),
        '111_0' => array('k1'=>3, 'k2'=>3),
        '111_1' => array('k2'=>2, 'k3'=>2),
        '111_2' => array('k3'=>1, 'k4'=>1)
);

foreach ($original as $key=>$sub) {
    list($realkey, $num) = explode('_', $key);
    foreach ($sub as $subkey => $value) {
        if ( isset($result[$realkey][$subkey]) 
             && $value < $result[$realkey][$subkey] ) {
            $result[$realkey][$subkey] = $value;
        }
    }
}
print_r($result);
于 2012-06-12T15:00:39.097 回答