1

我有一个多维数组:

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 函数来做这样的数组分组?

4

3 回答 3

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

工作演示

于 2012-07-12T08:53:24.930 回答
2

array_map()回调为 null 将完全符合您的要求。但是,它将具有索引编号而不是名称。

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

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

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

它真的是那么简单。大多数其他答案都很大而且没有必要。

注意:这假设数组的数量是固定的 - 如果它不固定,那么这将不起作用,然后使用 Florent 的答案。

于 2012-07-12T08:48:23.557 回答
0

You can do it with this function:

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

Hope this helps!

于 2012-07-12T08:51:58.737 回答