简体   繁体   English

根据 php 中提到的数组从多维数组中获取最大值

[英]Get the highest value from multidimensional array based on mentioned array in php

I am facing one issue for getting the highest value from array.我面临一个从数组中获得最高价值的问题。 I have two arrays.我有两个 arrays。 First array is below:第一个数组如下:

$catids = [239,240,238]

Second array is multidimensional array below:第二个数组是下面的多维数组:

  $categories = Array
  (
[0] => Array
    (
        [category_id] => 239
        [final_price] => 1999

    )

[1] => Array
    (
        [category_id] => 238
        [final_price] => 2990
    )

[2] => Array
    (
        [category_id] => 240
        [final_price] => 3500
    )
[3] => Array
    (
        [category_id] => 241
        [final_price] => 500
    )

)

Expected Out预计出局

Array
(
[category_id] => 240
[final_price] => 3500
)

In my input array catid 240 is having heighest value 3500.在我的输入数组中,catid 240 的最大值为 3500。

What I've tried我试过的

I have sorted the array by final_price in ascending order
usort($categories, function($a, $b) {
        return $a['final_price'] <=> $b['final_price'];
    });

Doing this in PHP is simple enough, you could just loop through the categories and check first that the category_id is in the array of category id's you are interested in, then compare the final_price against the current maximum...在 PHP 中执行此操作非常简单,您可以遍历类别并首先检查 category_id 是否在您感兴趣的类别 id 的数组中,然后将 final_price 与当前最大值进行比较...

$max = ["final_price" => PHP_INT_MIN];
foreach ( $categories as $category )    {
    if ( in_array($category["category_id"], $catids)
            && $category["final_price"] > $max["final_price"] ) {
        $max = $category;
    }
}
print_r($max);

which with the test data gives...这与测试数据给出了......

Array
(
    [category_id] => 240
    [final_price] => 3500
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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