Compare values of several arrays contained in a PHP array

Asked

Viewed 403 times

0

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

I would like in this case compare the products and return the product with lower price and higher quantity. In this case would be the product 3.

EDIT

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

  • 2

    But what if a product has the lowest price but quantity is not the highest? Or vice versa? How to process it. For example: 'producto4' => array(&#xA; 'preco'=> 1,&#xA; 'quantidade' => 50&#xA; ), If this product was also in your example

  • @Miguel really, in this case the price becomes the priority. I edited the question ! Thanks

  • 3

    I think it can be duplicated, https://answall.com/search?q=qsort+array+php

1 answer

1

From what I understand, 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() 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)
    }
}

Browser other questions tagged

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