How to sort an array of associative arrays by value of a given key in PHP?

前端 未结 19 1823
清酒与你
清酒与你 2020-11-21 23:34

Given this array:

$inventory = array(

   array(\"type\"=>\"fruit\", \"price\"=>3.50),
   array(\"type\"=>\"milk\", \"price\"=>2.90),
   array(\"         


        
19条回答
  •  旧巷少年郎
    2020-11-22 00:19

    $inventory = 
        array(array("type"=>"fruit", "price"=>3.50),
              array("type"=>"milk", "price"=>2.90),
              array("type"=>"pork", "price"=>5.43),
              );
    
    function pricesort($a, $b) {
      $a = $a['price'];
      $b = $b['price'];
      if ($a == $b)
        return 0;
      return ($a > $b) ? -1 : 1;
    }
    
    usort($inventory, "pricesort");
    // uksort($inventory, "pricesort");
    
    print("first: ".$inventory[0]['type']."\n\n");
    // for usort(): prints milk (item with lowest price)
    // for uksort(): prints fruit (item with key 0 in the original $inventory)
    
    // foreach prints the same for usort and uksort.
    foreach($inventory as $i){
      print($i['type'].": ".$i['price']."\n");
    }
    

    outputs:

    first: pork
    
    pork: 5.43
    fruit: 3.5
    milk: 2.9
    

提交回复
热议问题