Simulate mysql Join with a php array

Asked

Viewed 32 times

0

Good afternoon, everyone.

I have a two-dimensional associative array with the following data:

[0] => array ( "numArea" => '74', "quant" => 2 )
[1] => array ( "numArea" => '7', "quant" => 1 )
[2] => array ( "numArea" => '34', "quant" => 1 )
[3] => array ( "numArea" => '7', "quant" => 2 )
[4] => array ( "numArea" => '74', "quant" => 5 )
[5] => array ( "numArea" => '7', "quant" => 3 )

I need to create an array by merging the amounts of the same area. The result I need would look like this:

[0] => array ( "numArea" => '74', "quant" => 7 )
[1] => array ( "numArea" => '7', "quant" => 6 )
[2] => array ( "numArea" => '34', "quant" => 1 )

I have no idea how to do this. Can anyone help me?

1 answer

0


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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.