Can be done using the foreach
(not necessarily, can use other ties). In my case I used the most propitious logic that came to mind, create a new array with the new information. For this I created a variable verificaNumArea
where will be added the numArea
that I determined how PK
, then there will be no more than one numArea
equal, with this in mind I always did a check on the first line of the loop, which checks whether there is already a code equal to the numArea
from the loop, if it does not exist, a new array will be created with the positions [numArea
and quant]
, if it already exists it will recover the position of the numArea
in the variable verificaNumArea
, to find out what position the newArr
it belongs, with that already ready, just make the increment of the quant
, follow the code below.
$newArr = []; // Onde ficará o novo array com a somatória dos 'numArea'
$verificaNumArea = []; // Onde ficarão os 'numArea' para verificar as posições para atribuir a soma na 'quant'
//Array com valores
$arr = [
["numArea" => '74', "quant" => 2],
["numArea" => '7', "quant" => 1],
["numArea" => '34', "quant" => 1],
["numArea" => '7', "quant" => 2],
["numArea" => '74', "quant" => 5],
["numArea" => '7', "quant" => 3]
];
// Laço que irá percorrer cada item no array 'arr'
foreach($arr as $key => $item){
// Verifica se já existe o 'numArea' dentro do array 'verificaNumArea'
if(in_array($item["numArea"], $verificaNumArea)){
// Caso existe irá pegar a posição determinada da chave e fazer a soma
$newArr[array_search($item["numArea"], $verificaNumArea)]["quant"] += $item["quant"];
// Volta ao inicio e não termina o código a baixo
continue;
}
// Adicionar o 'numArea' na variavel 'verificaNumArea' para realizar verificações e não ocorrer duplicidades de 'numArea'
array_push($verificaNumArea, $item["numArea"]);
// Adiciona o no novo array 'newArr'
array_push($newArr, ["numArea" => $item["numArea"], "quant" => $item["quant"]]);
}
References:
- in_array
- array_search
- array_push
Arrays