Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

Merge Group Array in PHP

In php i have array like this

$the_array = Array(
   [0]=>Array([id]=>1,[value]=>10,[name]=>apple),
   [1]=>Array([id]=>1,[value]=>20,[name]=>orange),
   [2]=>Array([id]=>1,[value]=>30,[name]=>banana),

   [3]=>Array([id]=>2,[value]=>100,[name]=>car), 
   [4]=>Array([id]=>2,[value]=>200,[name]=>bicycle),
)

and try merge this arrays to gather result i want is :

$result = Array(
[0]=>Array([id]=>1,[value]=>60,[name]=>"apple,orange,banana"),  #value = 10+20+30
[1]=>Array([id]=>2,[value]=>300,[name]=>"car,bicyle"),
)

i try to do it with this way

function group_by($key, $data) {
        $result = array();
                    foreach($data as $val) {
                        if(array_key_exists($key, $val)){
                            $result[$val[$key]][] = $val;
                        }else{
                            $result[""][] = $val;
         }
}

return $result;
}

but it's not and result is wrong or incomplete and i have no access to values for create array like result

Thank you for your help

question from:https://stackoverflow.com/questions/65887917/merge-group-array-in-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would create an intermediary array which groups into array keys by id first, then use that to call combinations of array_column() with array_sum() and implode() to produce your sum value and combined name string.

$temp_array = [];
foreach ($the_array as $init) {
  // Initially, group them on the id key as sub-arrays
  $temp_array[$init['id']][] = $init;
}

$result = [];
foreach ($temp_array as $id => $arr) {
  // Loop once for each id ($temp_array has 2 elements from your sample)
  // And add an element to $result
  $result[] = [
    'id' => $id,
    // Sum the value subkeys
    // array_column() returns just the key 'value' as an array
    // array_sum() adds them
    'value' => array_sum(array_column($arr, 'value')),
    // implode the name subkeys into a string
    'name' => implode(',', array_column($arr, 'name'))
  ];
}

print_r($result);
Array
(
    [0] => Array
        (
            [id] => 1
            [value] => 60
            [name] => apple,orange,banana
        )

    [1] => Array
        (
            [id] => 2
            [value] => 300
            [name] => car,bicycle
        )

)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...