-3

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

原始数组

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
        )
    )
)
4

1 回答 1

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);

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

于 2012-09-19T09:13:47.077 回答