简体   繁体   English

PHP日期比较不正确

[英]PHP Date comparison not right

I am modifying a custom feature within Joomla/K2, but it's really only PHP involved. 我正在Joomla / K2中修改自定义功能,但实际上仅涉及PHP。 This functionality isn't available via any modules or extensions so I really need to figure it out. 此功能无法通过任何模块或扩展使用,因此我真的需要弄清楚。

I am outputting K2 articles and trying to sort by a date field which is an 'Extra Field' in K2. 我正在输出K2文章,并尝试按日期字段进行排序,该日期字段是K2中的“额外字段”。 It is stored in the database as a date string. 它作为日期字符串存储在数据库中。 My function to sort works, in that it changes the order of the items - but it does not work to get them in the correct sequence. 我的排序功能有效,因为它可以更改项目的顺序-但无法按正确的顺序获得它们。

function cmp($a, $b){
    global $array;
    return strcmp($array[$a][1], $array[$b][1]);
}


  $limit = 3;
  $limitstart = 0;

  foreach($items as $key=>$item) {

            $extraval = NULL;

            foreach ($item->extra_fields as $extraField){
                if($extraField->value != ''){
                    if($extraField->name == "Start Date"){
                      $extraval = strtotime($extra_field->value);
                    }
                }
            }

            $extrasort[$key] = Array();
            $extrasort[$key][0] = $item;
            $extrasort[$key][1] = $extraval;

          }

          sort($extrasort, 'cmp');

          $rows = Array();
          $total = $limit + $limitstart;

          for($i=$limitstart; $i<$total; $i++) {
            if(!empty($extrasort[$i][0])) {
              $rows[] = $extrasort[$i][0];
            }
          }

The output from this currently is: 当前的输出是:

1381525200
1380834000
1386795600

Which is not correct, (hopefully) obviously. (希望如此)显然是不正确的。

Any suggestions at all or tips would be so appreciated, I have been playing with this for hours and in general I am unsure about the 2D array. 任何建议或技巧都将不胜感激,我已经玩了好几个小时了,总体上我不确定2D阵列。

Thanks 谢谢

The callback function that sort uses is provided the two values that need to be compared. sort使用的回调函数提供了两个需要比较的值。 There's no need to go looking at a global array. 无需查看全局数组。 In this case, you're provided with the two elements in $extrasort, which are themselves arrays, so you just need to look at the elements you want to sort on. 在这种情况下,在$ extrasort中为您提供了两个元素,它们本身就是数组,因此您只需要查看要排序的元素即可。

Your function should (probably) be: 您的功能应该(可能)是:

function cmp($a, $b){
 return strcmp($a[1], $b[1]);
}

Thanks for your help Mike. 感谢您的帮助,迈克。 My solution was to convert the date into ISO (YYYY-MM-DD) format and sort using the function below: 我的解决方案是将日期转换为ISO(YYYY-MM-DD)格式,并使用以下功能进行排序:

function compareasc($v1, $v2) {
       if ($v1[1] == $v2[1]) return 0;
       return ($v1[1] < $v2[1])?-1:1;
}

usort($extrasort, 'compareasc');

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

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