Fetch a specific value of an array according to values of another array and show the value of another field

Asked

Viewed 182 times

0

I have two arrays, one called stock and the other called input. Both have the elements with the same key pair. Example:

Stockpile:

$estoque= array(
    array (
        'tamanho' => '33',
        'quantidade' => '0'
    ),
     array (
        'tamanho' => '34',
        'quantidade' => '0'
    ),
     array (
        'tamanho' => '37',
        'quantidade' => '1'
    ),
     array (
        'tamanho' => '35',
        'quantidade' => '3'
    )
);

Entree:

$entrada= array(
    array (
        'tamanho' => '33',
        'quantidade' => '1'
    ),
     array (
        'tamanho' => '34',
        'quantidade' => '3'
    ),
     array (
        'tamanho' => '35',
        'quantidade' => '5'
    ),
     array (
        'tamanho' => '37',
        'quantidade' => '9'
    )
);

Only I need to take the amount of the entry and enter it into the stock when the elements are the same size. I made a loop to go through the stock array, but I don’t know how to check if there is the same size in the other array but I don’t know how to show the value of the quantity of the element found. I thought about making two loops, but I believe that PHP should have a more appropriate function. . Can anyone tell me how it works? In logic it would look like this:

foreach ($estoque as $key => $produto) {
          if(in_array($produto['tamanho'],array_column($entrada,'tamanho'))){
                echo 'Entrada do tamanho ".$produto['tamanho']." é (mostrar a quantidade do elemento do array de entrada de acordo com o tamanho)';
          }
        }
  • Do you want to add the values in "quantity"? In the first array it has "size => 37 and quantity => 1", in the second "size => 37 and quantity => 9", then it would be in the first array "size => 37 and quantity => 10"?

  • Yes. I’ll even modify the post. I was able to check if it exists but I need to get the amount of the input according to the comparison. Ex. I found size 37 in both arrays. So how to get the amount value in the input array?

1 answer

2


Hello, the following code should solve your problem.

foreach ($entrada as $key => $value) {

    if(false !== $key_search = array_search($value['tamanho'], array_column($estoque, 'tamanho'))) {

        $estoque[$key_search]['quantidade'] += $entrada[$key]['quantidade'];
    }
}

To view the result:

print_r("<pre>");
print_r($estoque);
print_r("</pre>");

Browser other questions tagged

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