所以我有这2个数组。第一个包含一个数组,另一个包含两个数组。结果,它们像这样分组。
array(1) {
[0]=>
array(9) {
["id"]=>
int(9)
["product_group_id"]=>
int(9)
["sold_to"]=>
int(107824)
["value"]=>
int(19845)
["created_at"]=>
string(19) "2019-01-24 14:48:25"
["updated_at"]=>
string(19) "2019-01-24 14:48:25"
}
}
array(2) {
[0]=>
array(9) {
["id"]=>
int(17)
["product_group_id"]=>
int(8)
["sold_to"]=>
int(126124)
["value"]=>
int(15555)
["created_at"]=>
string(19) "2019-01-24 14:48:25"
["updated_at"]=>
string(19) "2019-01-24 14:48:25"
}
[1]=>
array(9) {
["id"]=>
int(20)
["product_group_id"]=>
int(8)
["sold_to"]=>
int(141877)
["value"]=>
int(10848)
["created_at"]=>
string(19) "2019-01-24 14:48:25"
["updated_at"]=>
string(19) "2019-01-24 14:48:25"
}
}
我想基于product_group_id
将第二个数组合并为一个数组
['id'=>“ 17,20”,'product_group_id'=>“ 9”,'sold_to'=>“ 107824,126124”]
答案 0 :(得分:1)
尝试一下:下面的测试用例
function groupImplode( $key, $array, $glue = ',' ){
$result = [];
foreach( $array as $index => $element ){
if( array_key_exists( $key, $element ) ){
if( isset( $result[ $element[$key] ] ) ){
//concat values
foreach( array_keys( $element ) as $elementKey ){
if( $elementKey !== $key )
$result[ $element[$key] ][ $elementKey ] .= $glue . $element[$elementKey];
}
}else
$result[ $element[$key] ] = $element;
}
}
return array_values( $result );
}
$myArray = [
['id' => 17, 'product_group_id' => 8, 'sold_to' => 126124, 'value' => 15555, 'created_at' => '2019-01-24 14:48:25', 'updated_at' => '2019-01-24 14:48:25' ],
['id' => 20, 'product_group_id' => 8, 'sold_to' => 141877, 'value' => 10848, 'created_at' => '2019-01-24 14:48:25', 'updated_at' => '2019-01-24 14:48:25' ],
];
$res = groupImplode( 'product_group_id', $myArray );
print_r($res);
答案 1 :(得分:1)
在“ product_group_id”上构建关联数组,然后使用array_values重置键。
foreach($arr as $sub){
foreach($sub as $item){
$new[$item["product_group_id"]][] = $item;
}
}
$new = array_values($new);