迭代数组并创建多维

时间:2017-01-17 14:05:11

标签: php arrays multidimensional-array

为简单起见,我有一个数组:

 Array (
[0] => Array
    (
        [content] => Item One
        [type] => Breakfast
    )
[1] => Array
    (
        [content] => Item Two
        [type] => Breakfast
    )
[2] => Array
    (
        [content] => Item One
        [type] => Lunch
    )
[3] => Array
    (
        [content] => Item One
        [type] => Dinner
    )
 )

创建一个新的多维数组的最有效方法是什么,它将在匹配键" type"?上结合使用?如下。目前试图在foreach。是否有内置功能?

 Array (
[0] => Array
    (
        [content] => Item One
        [type] => Breakfast
    ),
    (
        [content] => Item Two
        [type] => Breakfast
    )
[1] => Array
    (
        [content] => Item One
        [type] => Lunch
    ),
[2] => Array
    (
        [content] => Item One
        [type] => Dinner
    )
 )

2 个答案:

答案 0 :(得分:3)

您必须遍历输入数组并创建一个新的输出数组。看看这个简单的例子:

<?php
$input = [
    [
        'content' => 'Item One',
        'type' => 'Breakfast',
    ],
    [
        'content' => 'Item Two',
        'type' => 'Breakfast',
    ],
    [
        'content' => 'Item Three',
        'type' => 'Lunch',
    ],
    [
        'content' => 'Item Four',
        'type' => 'Dinner',
    ]
];
$output = [];

array_walk(
    $input,
    function($element) use (&$output) {
        $output[$element['type']][] = $element;
    }
);
print_r($output);

上面的输出显然是:

Array
(
    [Breakfast] => Array
        (
            [0] => Array
                (
                    [content] => Item One
                    [type] => Breakfast
                )

            [1] => Array
                (
                    [content] => Item Two
                    [type] => Breakfast
                )

        )

    [Lunch] => Array
        (
            [0] => Array
                (
                    [content] => Item Three
                    [type] => Lunch
                )

        )

    [Dinner] => Array
        (
            [0] => Array
                (
                    [content] => Item Four
                    [type] => Dinner
                )

        )

)

当然,您可以在创建的数组中放置您想要的任何元素和结构。对于这个例子,我只接受了原始元素,因为这与演示如何轻松遍历数组无关。

如果您坚持输出数组中的数字键序列,那么您只需使用print_r(array_values($output));代替print_r($output) ...

答案 1 :(得分:0)

您可以循环浏览并按TYPE

将它们推送到新数组中

例如:

$newitmes = [];
 foreach($arr as $item){
    $type = $item['type'];
    $newitmes[$type][] = $item;
 }
print_r($newitmes);

希望这能回答你的问题。