按键合并数组并为值创建新数组

时间:2012-09-19 08:46:06

标签: php arrays merge key

我有一个数组需要按键合并,并使用该键的值创建一个新数组。我搜索和搜索没有结果。任何帮助都会很棒!

原始数组

Array
(
    [0] => Array
    (
        [name] => Key 1
        [value] => Value 1
    )

    [2] => Array
    (
        [name] => Key 1
        [value] => Value 2
    )

    [3] => Array
    (
        [name] => Key 2
        [value] => Value 1
    )

    [4] => Array
    (
        [name] => Key 1
        [value] => Value 3
    )

    [5] => Array
    (
        [name] => Key 2
        [value] => Value 2
    )
)

最终数组应该如下所示

Array
(
    [0] => Array
    (
        [name] => Key 1
        [value] => Array
        (
            [0] => Value 1

            [1] => Value 2

            [2] => Value 3
        )
    )

    [1] => Array
    (
        [name] => Key 2
        [value] => Array
        (
            [0] => Value 1

            [1] => Value 2
        )
    )
)

1 个答案:

答案 0 :(得分:1)

<?php 
$array =    Array
(
    0 => Array
    (
        'name' => 'Key 1',
        'value' => 'Value 1'
    ),

    2 => Array
    (
        'name' => 'Key 1',
        'value' => 'Value 2'
    ),

    3 => Array
    (
        'name' => 'Key 2',
        'value' => 'Value 1'
    ),

    4 => Array
    (
        'name' => 'Key 1',
        'value' => 'Value 3'
    ),

    5 => Array
    (
        'name' => 'Key 2',
        'value' => 'Value 2'
    )
);
$tmpArray = array(); 
foreach ($array as $smallArray) {
if(!is_array($tmpArray[$smallArray['name']]))
    $tmpArray[$smallArray['name']] = array();

$tmpArray[$smallArray['name']][] = $smallArray['value'];
}
$finalArray = array();
foreach ($tmpArray as $key => $value) {
    $someArray['name'] = $key;
    $someArray['value'] = $value;
    $finalArray[] = $someArray;
}

print_r($finalArray);

我为你写了解决方案,但下次你应该先尝试自己