PHP按索引分组数组

时间:2012-07-12 08:45:34

标签: php arrays

我有一个多维数组:

Array
(
[type] => Array
(
    [0] => text
    [1] => portfolio
    [2] => slide
    [3] => text
)

[grid] => Array
(
    [0] => 3
    [1] => 5
    [2] => 3
    [3] => 4
)

[title] => Array
(
    [0] => title1
    [3] => title2
)

[content] => Array
(
    [0] => content1
    [3] => content2
)

[item] => Array
(
    [1] => 6
    [2] => 7
)

[pagination] => Array
(
    [1] => 8
)

[order] => Array
(
    [1] => desc
    [2] => asc
)

)

并希望按照数组中给出的[type]键对其进行分组:

Array (

[0] => Array (
        [type] => text
        [grid] => 3
        [title] => title1
        [content] => content1
    )

[1] => Array (
        [type] => portfolio
        [grid] => 5
        [item] => 6
        [pagination] => 1
        [order] => desc
    )

[2] => Array (
        [type] => slide
        [grid] => 3
        [item] => 7
        [order] => asc
    )

[3] => Array (
        [type] => text
        [grid] => 4
        [title] => title2
        [content] => content2
    )

有没有办法或PHP函数来做这样的数组分组?

3 个答案:

答案 0 :(得分:6)

这段代码实现了:

$result = array();
foreach ($array as $key => $data) {
    foreach ($data as $offset => $value) {
        if (isset($result[$offset])) {
            $result[$offset][$key] = $value;
        } else {
            $result[$offset] = array($key => $value);
        }
    }
}

<强> Working DEMO

答案 1 :(得分:2)

回调为

array_map()的回调将完全符合您的要求。但是它会有索引号而不是名字。

如果您编写自己的回调,那么您可以返回一个包含所需名称的数组。

因为显然人们想要实际的代码:

array_map(null, $type_array, $grid_array, $title_array, $content_array, $item_array);

真的很简单。大多数其他答案都是如此之大和不必要。

注意:这假设有一定数量的数组 - 如果它没有被修复,那么这将不起作用,然后继续使用Florent的答案。

答案 2 :(得分:0)

您可以使用此功能执行此操作:

$type_array = array('text', 'portfolio', 'slide', 'text');
$grid_array = array(3, 5, 3, 4);
$title_array = array(0 => 'title1', 3 => 'title2');
$content_array = array(0 => 'content1', 3 => 'content2');
$item_array = array(1 => 6, 2 => 7);


function group_arrays($type_array, $grid_array, $title_array, $content_array, $item_array) {
    $temp_array = array();

    for($i = 0; $i < count($type_array); $i++) {
        $temp_array[$i] = array( 'type' => @$type_array[$i],
                                 'grid' => @$grid_array[$i],
                                 'title' => @$title_array[$i],
                                 'content' => @$content_array[$i],
                                 'item' => @$item_array[$i]);
    }

    return $temp_array;
}

print_r(group_arrays($type_array, $grid_array, $title_array, $content_array, $item_array));

希望这有帮助!