如何提取数组键和值以获取PHP中的新数组?

时间:2015-03-06 07:01:05

标签: php arrays

我有一个关联数组,其中包含键category_id和item_code及其各自的值,如下所示

$arr = Array
(
 [0] => Array
    (
        [category_id] => 1
        [item_code] => RED 
    )
[1] => Array
    (
        [category_id] => 1
        [item_code] => GREEN
    )
[2] => Array
    (            
        [category_id] => 2
        [item_code] => BLUE
    )
[3] => Array
    (
        [category_id] => 3
        [item_code] => YELLOW
    )
[4] => Array
    (
        [category_id] => 3
        [item_code] => WHITE
    )
[5] => Array
    (
        [category_id] => 3
        [item_code] => BLACK
    )
);

现在我想提取这个数组来获得像这样的新数组

$new_arr = Array
 (
 [0] => Array
    (
        [0] => RED
        [1] => GREEN
    )
[1] => Array
    (
        [0] => BLUE
    )
[2] => Array
    (
        [0] => YELLOW
        [1] => WHITE
        [2] => BLACK
    )   
);

我怎样才能获得这个新阵列?如果您有任何想法,请给我一些建议。感谢

1 个答案:

答案 0 :(得分:2)

你走了:

foreach($arr as $v) {
  $new_arr[$v['category_id']][] = $v['item_code'];
}
$new_arr = array_values($new_arr);