I have the following JSON (I will show a dd of the $data_concepts variable):
array:3 [
0 => {#2408
+"total": "1300"
+"concepto": "AHORRO SOLIDARIO 1 B"
+"alias": "2AS"
+"tipo": 2
+"code": "2AS"
}
1 => {#2377
+"total": "700"
+"concepto": "AHORRO SOLIDARIO 1 M"
+"alias": "2AS"
+"tipo": 2
+"code": "2AS.0"
}
2 => {#2391
+"total": "9815.670000000002"
+"concepto": "AHORRO SOLIDARIO 2 B"
+"alias": "24S"
+"tipo": 2
+"code": "24S."
}
]
I am trying to group the data by alias, that is, if the alias field is repeated, get another JSON with a single alias and the sum of the total field of all of them.
That is, something like this:
array:2 [
0 => {#2408
+"total": "2000"
+"concepto": "AHORRO SOLIDARIO 1 B"
+"alias": "2AS"
+"tipo": 2
+"code": "2AS"
}
1 => {#2391
+"total": "9815.670000000002"
+"concepto": "AHORRO SOLIDARIO 2 B"
+"alias": "24S"
+"tipo": 2
+"code": "24S."
}
]
I am trying this way:
$conceptss= [];
foreach ($data_concepts as $clave => $conceptss) {
if (!empty($conceptss->alias)) {
if(!empty($concepts)) {
if (in_array($conceptss->alias, $concepts[$clave])) {
continue;
} else {
array_push($concepts, $conceptss);
// dd($concepts);
}
} else {
array_push($concepts, $conceptss);
}
}
}
But this throws an error, any ideas or tips? Any help is helpful and much appreciated, thanks.
I get the data from a query to my database, the query is as follows:
$data_concepts = DB::table('processed_payroll_concepts')
->select(DB::raw('sum(processed_payroll_concepts.amount) as Total, processed_payroll_concepts.name as Concepto, processed_payroll_concepts.alias as Alias, processed_payroll_concepts.cat_concept_type_id as Tipo, processed_payroll_concepts.code as Code'))
->leftJoin('processed_payrolls', 'processed_payrolls.id', '=', 'processed_payroll_concepts.processed_payroll_id')
->where('processed_payrolls.payroll_id', $id)
// ->whereNotNull('alias')
->groupBy('processed_payroll_concepts.name')
->groupBy('processed_payroll_concepts.alias')
->groupBy('processed_payroll_concepts.cat_concept_type_id')
->groupBy('processed_payroll_concepts.code')
->get();
As I said in the comments, I don't understand why you want that output, because the values of
code
andconcepto
are different.Still, I think this might work for you:
So it generates this output:
which comes to coincide with what you ask.
Explanation
$output
where we will store the data of each cycle, related by keys that match the propertyalias
$output
there is the key that corresponds to the value of the propertyalias
of the object iterated in that cycle of the loop.Then, if you need it in json format , you can do the following:
Tell us if it works for you.