简体   繁体   English

从嵌套数组中查找最新日期

[英]Find the most recent date from a nested array

I have a Multilevel Array ( See array structure picture below ) and I need to get the sub-nested array with the higher date value . 我有一个Multilevel Array请参见下面的数组结构图 ),我需要获取具有较高date value的子嵌套数组。

I was wondering if there is a straight forward way to sort sub-nested arrays by date value or get the highest date value ? 我想知道是否有一种直接的方法可以按date value对子嵌套数组进行排序或获得最高的date value

Array Map 阵列图

To do that, usort() function will be useful: 为此, usort()函数将非常有用:

usort($rgData, function($rgX, $rgY)
{
   $x = strtotime($rgX['date']);
   $y = strtotime($rgY['date']);
   return $x<$y?-1:$x!=$y;
});
//var_dump($rgData);

if you want to get highest value, then it will be ['date'] key of last element after doing the sort above. 如果您想获得最高价值,那么经过上述排序后,它将是最后一个元素的['date']键。

Edit: if you're sure that format will be exactly same as on picture always, you can use direct string comparison via strcmp (that would be probably faster) 编辑:如果您确定格式将始终与图片上的格式完全相同,则可以通过strcmp使用直接字符串比较(这可能会更快)

How about using usort() : 如何使用usort()

$input = array(
    array('date' => '2013-09-11 13:08:40 +0000'),
    array('date' => '2013-09-11 13:09:17 +0000'));

usort($input, function(array $a, array $b) {
    $aTimestamp = strtotime($a['date']);
    $bTimestamp = strtotime($b['date']);

    if($aTimestamp == $bTimestamp) return 0;
    return $aTimestamp < $bTimestamp;
});

print_r($input); //$input[0] has the latest date value

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

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