简体   繁体   中英

PHP Search an Array for maximum key / value pairs

I have a array list, How can I get with PHP the highest key value pair in an array?

   array:4 [
  0 => array:2 [
    "free_shipping" => true
    "coupon_amt" => 20
  ]
  1 => array:2 [
    "coupon_amt" => 120
    "free_shipping" => false
  ]
  2 => array:2 [
    "free_shipping" => false
    "coupon_amt" => 100
  ]
  3 => array:2 [
    "coupon_amt" => 200
    "free_shipping" => true
  ]
]

Any ideas or suggestions on how I can or should do this?

    array:4 [
  0 => array:2 [
    "free_shipping" => true
    "coupon_amt" => 200
  ]
]

A simple loop seems the best option to me.

$max = null;
foreach ($array as $part) {
    if ($max === null || $part['coupon_amt'] > $max['coupon_amt']) {
        $max = $part;
    }
}

Could you try this:

First Convert the array to collection

$collection = collect($array);

And then sort it

$sorted = $collection->sortByDesc('coupon_amt');

then if you want it to be array again just do this

$array = $sorted->toArray();

then just get the first array

$first = $array[0];

Hope it helps!

Use the collections' available methods such as max and where .

<?php

$collection = collect($array);

print_r($collection->where('coupon_amt',$collection->max('coupon_amt'))->all());

$collection = collect($array);

print_r($collection->where('coupon_amt',$collection->max('coupon_amt'))->all());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM