I am trying to unique values from this for loop and organized them Payload:
$name = ['Mazda','Mazda','Lexus', 'Lexus']; $count = [1,1,1,1]; $gp =[54,35,23,46];
I Have a payload that I am trying to organized the data into arrays based on the “unique” name so I can total the results and eventually pass it to a PDF. The column that I am trying to create is a total Column.
example.
NAME | C | GP | ------|---|----| Mazda | 2 | 89 | Lexus | 2 | 69 |
what is the best way to go about this? I thought about doing array_unique
Advertisement
Answer
here is my approach
// Data $name = ['Mazda','Mazda','Lexus', 'Lexus']; $count = [1,1,1,1]; $gp =[54,35,23,46]; // declare result array $result = []; // do Looping for($i = 0; $i < count($name); $i++) { $result[ $name[$i] ] = [ "C" => ($result[ $name[$i] ]['C'] ?? 0) + $count[$i], "GP" => ($result[ $name[$i] ]['GP'] ?? 0) + $gp[$i] ]; } print_r($result);
Demo : https://3v4l.org/U3nQ0