我有一个多维的数组
Array (
[0] => Array ( [id] => 2 [id_product_attribute] => 9 )
[1] => Array ( [id] => 2 [id_product_attribute] => 10 )
[2] => Array ( [id] => 2 [id_product_attribute] => 8 )
[3] => Array ( [id] => 3 [id_product_attribute] => 50 )
)
我想将此数组转换为此格式
Array (
[0] => Array ( [id] => 2 [id_product_attribute] => Array(9,10,8) )
[1] => Array ( [id] => 3 [id_product_attribute] => Array (50) )
)
答案 0 :(得分:1)
循环遍历第一个数组并将值合并到第二个数组中,然后使用array_values
来排序第一个数组:(Sandbox)
$orig = array(
0 => array( 'id' => 2, 'id_product_attribute' => 9 ),
1 => array( 'id' => 2, 'id_product_attribute' => 10 ),
2 => array( 'id' => 2, 'id_product_attribute' => 8 ),
3 => array( 'id' => 3, 'id_product_attribute' => 50 )
);
$array = [];
foreach ($orig as $o) {
if (!isset($array[$o['id']])) {
$array[$o['id']] = ['id' => $o['id'], 'id_product_attribute' => []];
}
$array[$o['id']]['id_product_attribute'][] = $o['id_product_attribute'];
}
// to get the first array with indexes 0,1...
$result = array_values($array);
print_r($result);