查找深层嵌套数组中特定键的最低值

时间:2017-01-05 19:07:07

标签: php algorithm sorting

给定具有以下结构的数组:

$orders = [
     0 => [
              'volume' => 1926,
              'lowPrice' => 1000.00,
              'date' => 2016-12-29 00:45:23
     ],
     1 => [
              'volume' => 145,
              'lowPrice' => 1009.99,
              'date' => 2016-12-31 14:23:51
     ],
     2 => [
              'volume' => 19,
              'lowPrice' => 985.99,
              'date' => 2016-12-21 09:37:13
     ],
     3 => [
              'volume' => 2984,
              'lowPrice' => 749.99,
              'date' => 2017-01-01 19:37:22
     ],
     // ...
]

我正在寻找找到lowPrice最低值的最佳效果。 $orders的大小可能会超过500个项目。对于给定的数组,结果如下:

$lowestPrice = $this->findLowestPrice($orders);

echo $lowestPrice; // 749.99

2 个答案:

答案 0 :(得分:1)

提取lowPrice数组并找到min()

echo min(array_column($orders, 'lowPrice'));

由于这些似乎是花车,您可能需要number_format()money_format()

答案 1 :(得分:0)

如果您只对最低价格(不是数组中的索引或其他内容)的价值感兴趣,可以使用array_reduce

$orders = [
     0 => [
              'volume' => 1926,
              'lowPrice' => 1000.00,
              'date' => "2016-12-29 00:45:23"
     ],
     1 => [
              'volume' => 145,
              'lowPrice' => 1009.99,
              'date' => "2016-12-31 14:23:51"
     ],
     2 => [
              'volume' => 19,
              'lowPrice' => 985.99,
              'date' => "2016-12-21 09:37:13"
     ],
     3 => [
              'volume' => 2984,
              'lowPrice' => 749.99,
              'date' => "2017-01-01 19:37:22"
     ],
];

$lowestPrice = array_reduce(
    $orders,
    function($c, $v)
    {
        if ($c === null)
            return $v["lowPrice"];

        return $v["lowPrice"] < $c ? $v["lowPrice"] : $c;
    }
);