I run into a problem, I have an associative array in which I have cities and subpoenas there may be repeated cities, so the idea is to group the cities and add their subpoenas so that there are no cities with jumbled individual subpoenas, but to group them and add said subpoena per city no It works for me, I managed to get it out with 3 arrangements, the correct values, but when inserting more data in the associative array, it happens that it becomes distorted and distributes the subpoenas for the other cities, but in the end they added up the total number of subpoenas that I have, only that it distributes them wrongly in all the cities that I have, I have this code:
introducir el código aquí
<?php
//tenemos la data en un array asociativo
$datos=[
[
"ciudad"=>"medellin",
"comparendos"=>1,
],
[
"ciudad"=>"cali",
"comparendos"=>5,
],
[
"ciudad"=>"medellin",
"comparendos"=>2,
],
];
//contamos los elementos del arreglo principal
$total_array_principal= count($datos);
/*creamos un array para ir almacenando los datos finales agrupados por
ciudades y sumando los comparendos de la misma ciudad*/
$datos_finales=[];
for($i=0;$i<$total_array_principal;$i++){
$ciudad=$datos[$i]['ciudad'];
$comparendos=$datos[$i]['comparendos'];
/*aca validamos la ciudad no esta en la busqueda en los datos finales la aññadimos
y si ya esta eliminamos el indice le sacamos el valor e comparendos
lo sumamos en este y elimianmos el otro y metemos este en array push
*/
$found_key = array_search($ciudad, array_column($datos_finales, 'ciudad'));
//esa funcion me retorna el indice del array entonces si no lo encuentra retorna vacio y si si numerico
if(is_numeric($found_key)){
$comparendo=$datos_finales[$found_key]['comparendos']+$comparendos;
//$comparendos=$comparendo +$comparendos;
//$ciudad=$datos_finales[$found_key]['ciudad'];
$insertar=[
'ciudad'=>$ciudad,
'comparendos'=>$comparendo
];
array_push($datos_finales,$insertar);
unset($datos_finales[$found_key]);
}else{
$insertar=[
'ciudad'=>$ciudad,
'comparendos'=>$comparendos
];
array_push($datos_finales,$insertar);
}
}
foreach($datos_finales as $data){
echo "ciudad ".$data['ciudad']." comparendo ".$data['comparendos'];
echo "<br>";
}
introducir el código aquí
A simple way would be to group by cities in a new array whose main key is precisely the name of the city. So every time you refer to a specific city, you will go to the same index of the new array.
So, in your example, the first step scanning your array would give us this result:
but when we find "medellin" again, and add the subpoenas:
and in the end the new array will have two main keys "medellin" and "cali", and each one, the fields that you already had, "city" and "comparendos".
Finally, and if necessary, the new array could be reconverted to a non-associative one (with a numeric primary key) so that it would have the structure of your initial one.