数组中的输出数组按公共索引分组

时间:2011-07-22 17:06:24

标签: php arrays indexing grouping

我有一个数组,如下所示。我想要的输出是按商店分组,然后将所有相关的数量和面额连接到这些数组中(我认为?)。我已经展示了所需的输出。

CURRENT ARRAY

Array
(
    [denomination] => Array
        (
            [0] => 25
            [1] => 50
            [2] => 100
            [3] => 200
        )

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

    [store] => Array
        (
            [0] => candy store
            [1] => candy store
            [2] => book store
            [3] => candy store
        )

)

期望的输出

Array
(
    [candy store] => Array
        (
            [0] => Array
                (
                    [denomination] => Array
                        (
                            [0] => 25
                            [1] => 50
                            [2] => 200
                        )

                )

            [1] => Array
                (
                    [quantity] => Array
                        (
                            [0] => 1
                            [1] => 1
                            [2] => 4
                        )
                )

        )

    [book store] => Array
        (
            [0] => Array
                (
                    [denomination] => Array
                        (
                            [0] => 100
                        )

                )

            [1] => Array
                (
                    [quantity] => Array
                        (
                            [0] => 2
                        )
                )
        )

)

1 个答案:

答案 0 :(得分:0)

$result = array();
foreach ($array['store'] as $index => $type) {
  $result[$type]['denomination'][] = $array['demoniation'][$index];
  $result[$type]['quantity'][] = $array['quantity'][$index];
}

这不完全是你指定为“所需输出”的内容,但我没有看到原因,为什么应该将denomination - 和quantity - 数组放入其他数组中。

但是,如果这有任何理由,你可以得到类似的

$result = array();
foreach ($array['store'] as $index => $type) {
  $result[$type][0]['denomination'][] = $array['demoniation'][$index];
  $result[$type][1]['quantity'][] = $array['quantity'][$index];
}