Compare values of several arrays contained in an array in PHP

0
<?php
    $productos = array(
      'producto1' => array(
           'preco'=> 25,
           'quantidade' => 5
       ),
      'producto2' => array(
           'preco'=> 20,
           'quantidade' => 50
       ),
      'producto3' => array(
           'preco'=> 10,
           'quantidade' => 100
       ),
    );
?>

In this case, I would compare the products and return the product with a lower price and more quantity. In that case it would be product 3.

EDIT

If a product has the lowest price but quantity is not the highest, the price should be the priority.

    
asked by anonymous 27.11.2017 / 10:33

1 answer

0

As I understood, in the end the price should always be the priority. Anyway, you can use array_multisort() to sort your array and then return the contents of the first index.

<?php
    $productos = {...};

    foreach ($productos as $key => $row) {
       $preco[$key]  = $row['preco'];
       $quantidade[$key] = $row['quantidade'];
    }

    array_multisort($preco, SORT_ASC, $quantidade, SORT_DESC, $productos);

    $menor = $productos[0];
?>

The var_dump() of the array will show:

array(3) {
    ["producto3"]=> array(2) {
         ["preco"]=> int(10)
         ["quantidade"]=> int(100)
    }
    ["producto2"]=> array(2) {
         ["preco"]=> int(20)
         ["quantidade"]=> int(50)
    }
    ["producto1"]=> array(2) {
         ["preco"]=> int(25)
         ["quantidade"]=> int(5)
    }
}
    
27.11.2017 / 17:10