从嵌套数组中获取最大日期

huangapple go评论80阅读模式
英文:

Get max date from a nested array

问题

如何从以下数组中获取最大的到期日期?到期日期始终是具有键5的值数组中的值,即$results['values'][5]

我知道可以对于简单的数组执行以下操作:

$max = max(array_map('strtotime', $arr));
echo date('d F Y', $max);

如何在嵌套数组中实现相同的效果?

英文:

If I have the following array how can I get the max expiry date? The expiry date is always the value in the values array with key 5 i.e. $results['values']['5']

  array (
     0 => 
       array (
         'values' => 
            array (
              1 => '123456',
              2 => 'Blue',
              3 => 'Container',
              4 => '03-01-2020',  // start date
              5 => '03-01-2021',  // exp date
              6 => '',
              7 => '',
           ),
        ),
     1 => 
       array (
         'values' => 
            array (
              1 => '21312',
              2 => 'Green',
              3 => 'Box',
              4 => '2019-04-12',  // start date
              5 => '',            //exp date
              6 => '',
              7 => '',
            ),
         ),
     2 => 
       array (
         'values' => 
            array (
              1 => '434324',
              2 => 'Orange',
              3 => 'Box',
              4 => '2018-04-28', // start date
              5 => '2019-04-23', // exp date
              6 => '',
              7 => '',
            ),
      ),
  )

I know I can do something as follows for a simple array:

 $max = max(array_map('strtotime', $arr));
 echo date('d F Y', $max);

How can I achieve the same with a nested array?

答案1

得分: 3

自定义函数可提取到期日期并一次性使用 strtotime,因为您已经在使用 array_map

$expiryDates = array_map(static function ($entry) {
  return strtotime($entry['values'][5]);
}, $input);

echo date('d F Y', max($expiryDates));

演示:https://3v4l.org/AiFtA

奖励 - 使用 PHP 7.4 短闭包:

$expiryDates = array_map(fn($entry) => strtotime($entry['values'][5]), $input);
echo date('d F Y', max($expiryDates));
英文:

Since you're already using array_map, you may use a custom function that grabs the expiry date and uses strtotime on it in one go:

$expiryDates = array_map(static function ($entry) {
  return strtotime($entry['values'][5]);
}, $input);

echo date('d F Y', max($expiryDates));

Demo: https://3v4l.org/AiFtA

Bonus - using PHP 7.4 short closures:

$expiryDates = array_map(fn($entry) => strtotime($entry['values'][5]), $input);
echo date('d F Y', max($expiryDates));

huangapple
  • 本文由 发表于 2020年1月3日 17:57:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576453.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定