PHP - 如何在数组中合并数组

时间:2013-06-11 09:52:44

标签: php array-merge

如何在php中合并n个数组。我的意思是我怎样才能做到这样的工作:
array_merge(from : $result[0], to : $result[count($result)-1])

array_merge_recursive(from: $result[0], to : $result[count($result) -1])


其中$result是一个包含多个数组的数组,如下所示:

$result = Array(
0 => array(),//associative array
1 => array(),//associative array
2 => array(),//associative array
3 => array()//associative array
)

我的结果是:

$result = Array(
    0 => Array(
        "name" => "Name",
        "events" => 1,
        "types" => 2
    ),
    1 => Array(
        "name" => "Name",
        "events" => 1,
        "types" => 3
    ),
    2 => Array(
        "name" => "Name",
        "events" => 1,
        "types" => 4
    ),
    3 => Array(
        "name" => "Name",
        "events" => 2,
        "types" => 2
    ),
    4 => Array(
        "name" => "Name",
        "events" => 3,
        "types" => 2
    )
)

我需要的是

$result = Array(
"name" => "name",
"events" => array(1,2,3),
"types" => array(2,3,4)
)

4 个答案:

答案 0 :(得分:151)

array_merge可以使用可变数量的参数,因此只需要一点call_user_func_array个诡计就可以将$result数组传递给它:

$merged = call_user_func_array('array_merge', $result);

这基本上就像你输入的那样:

$merged = array_merge($result[0], $result[1], .... $result[n]);

更新

现在使用5.6,我们有... operator将数组解包到参数中,所以你可以:

$merged = array_merge(...$result);

并得到相同的结果。 *

*只要在解压缩数组中有整数键,结果相同,否则会出现E_RECOVERABLE_ERROR : type 4096 -- Cannot unpack array with string keys错误。

答案 1 :(得分:3)

我非常喜欢complex857的答案,但它对我不起作用,因为我的数组中有数字键需要保留。

我使用+运算符来保留键(如PHP array_merge with numerical keys中所述),并使用array_reduce合并数组。

因此,如果要在保留数字键的同时合并数组中的数组,可以按如下方式进行:

<?php
$a = [
    [0 => 'Test 1'],
    [0 => 'Test 2', 2 => 'foo'],
    [1 => 'Bar'],
];    

print_r(array_reduce($a, function ($carry, $item) { return $carry + $item; }, []));
?>

结果:

Array
(
    [0] => Test 1
    [2] => foo
    [1] => Bar
)

答案 2 :(得分:3)

如果您愿意:

  • 检查进入array_merge的每个参数实际上是一个数组
  • 在其中一个数组中指定要合并的特定属性

您可以使用此功能:

function mergeArrayofArrays($array, $property = null)
{
    return array_reduce(
        (array) $array, // make sure this is an array too, or array_reduce is mad.
        function($carry, $item) use ($property) {

            $mergeOnProperty = (!$property) ?
                    $item :
                    (is_array($item) ? $item[$property] : $item->$property);

            return is_array($mergeOnProperty)
                ? array_merge($carry, $mergeOnProperty)
                : $carry;
    }, array()); // start the carry with empty array
}

让我们看看它在行动..这里是一些数据:

简单结构:要合并的纯数组数组。

$peopleByTypesSimple = [
    'teachers' => [
            0  => (object) ['name' => 'Ms. Jo', 'hair_color' => 'brown'],
            1  => (object) ['name' => 'Mr. Bob', 'hair_color' => 'red'],
    ],

    'students' => [
            0  => (object) ['name' => 'Joey', 'hair_color' => 'blonde'],
            1  => (object) ['name' => 'Anna', 'hair_color' => 'Strawberry Blonde'],
    ],

    'parents' => [
            0  => (object) ['name' => 'Mr. Howard', 'hair_color' => 'black'],
            1  => (object) ['name' => 'Ms. Wendle', 'hair_color' => 'Auburn'],
    ],
];

不太简单:数组数组,但希望指定忽略 计数

$peopleByTypes = [
    'teachers' => [
        'count' => 2,
        'people' => [
            0  => (object) ['name' => 'Ms. Jo', 'hair_color' => 'brown'],
            1  => (object) ['name' => 'Mr. Bob', 'hair_color' => 'red'],
        ]
    ],

    'students' => [
        'count' => 2,
        'people' => [
            0  => (object) ['name' => 'Joey', 'hair_color' => 'blonde'],
            1  => (object) ['name' => 'Anna', 'hair_color' => 'Strawberry Blonde'],
        ]
    ],

    'parents' => [
        'count' => 2,
        'people' => [
            0  => (object) ['name' => 'Mr. Howard', 'hair_color' => 'black'],
            1  => (object) ['name' => 'Ms. Wendle', 'hair_color' => 'Auburn'],
        ]
    ],
];

运行它

$peopleSimple = mergeArrayofArrays($peopleByTypesSimple);
$people = mergeArrayofArrays($peopleByTypes, 'people');

结果 - 两者都返回:

Array
(
    [0] => stdClass Object
        (
            [name] => Ms. Jo
            [hair_color] => brown
        )

    [1] => stdClass Object
        (
            [name] => Mr. Bob
            [hair_color] => red
        )

    [2] => stdClass Object
        (
            [name] => Joey
            [hair_color] => blonde
        )

    [3] => stdClass Object
        (
            [name] => Anna
            [hair_color] => Strawberry Blonde
        )

    [4] => stdClass Object
        (
            [name] => Mr. Howard
            [hair_color] => black
        )

    [5] => stdClass Object
        (
            [name] => Ms. Wendle
            [hair_color] => Auburn
        )

)

额外的乐趣: 如果要在数组或对象中单独输出一个属性,例如来自人物对象(或关联数组)的数组的“名称”,则可以使用此函数

function getSinglePropFromCollection($propName, $collection, $getter = true)
{
    return (empty($collection)) ? [] : array_map(function($item) use ($propName) {
        return is_array($item) 
            ? $item[$propName] 
            : ($getter) 
                ? $item->{'get' . ucwords($propName)}()
                : $item->{$propName}
    }, $collection);
}

getter用于可能受保护/私有的对象。

$namesOnly = getSinglePropFromCollection('name', $peopleResults, false);

返回

Array
(
    [0] => Ms. Jo
    [1] => Mr. Bob
    [2] => Joey
    [3] => Anna
    [4] => Mr. Howard
    [5] => Ms. Wendle
)

答案 3 :(得分:0)

试试这个

$result = array_merge($array1, $array2);

或者,您可以使用执行联合的+ op代替array_merge:

$array2 + array_fill_keys($array1, '');