合并其中父数组的某些值不等于的数组

时间:2015-01-23 21:29:55

标签: php arrays array-merge

我是一组数组,看起来像那样:

$messages = array (
  0 => 
     array(
     'keyT' => 'id.key'
     'mess' => array(
         array(1,0)
     )
...
)

我想合并mess不等于'keyT'的数组的foreach ($messages as $k => $current) { foreach ($messages as $ke => $all) { if ($current['keyT'] == $all['keyT']) { array_merge( ... ) } } } 个属性。 我跑了阵列:

{{1}}

但这并不能让我任何结果。也许有人可以帮助我。谢谢!

1 个答案:

答案 0 :(得分:0)

试试此代码

$messages = array(
    0 =>
    array(
        'keyT' => 'A',
        'mess' => array(
            array(1, 0)
        )
    ),
    1 =>
    array(
        'keyT' => 'A',
        'mess' => array(
            array(1, 2)
        )
    ),
    2 =>
    array(
        'keyT' => 'B',
        'mess' => array(
            array(3, 4)
        )
    )
);

$result = array();
foreach ($messages as $msg) {
    $key = $msg['keyT'];
    if (!isset($result[$key])) {
        $result[$key] = array();
    }
    $result[$key] = array_merge($result[$key], $msg['mess']);
}

print_r($result);

输出

Array
(
    [A] => Array
        (
            [0] => Array
                (
                    [0] => 1
                    [1] => 0
                )

            [1] => Array
                (
                    [0] => 1
                    [1] => 2
                )

        )

    [B] => Array
        (
            [0] => Array
                (
                    [0] => 3
                    [1] => 4
                )

        )

)