按日期排序foreach给出警告:usort()期望参数1为数组,给定为null
I have a .php that retrieve fields from my Joomla database and then echo them with a foreach function:
<?php
$jquery1 = "SELECT `fulltext`,alias,metakey,publish_up,metadesc FROM xxx_content WHERE catid=22 AND state= '1'";
$jdb1->setQuery( $jquery1 );
$jfeed1= $jdb1->loadObjectList();
foreach ($jfeed1 as $jitem1):
?>
<li>
<div>
<?php
$oldLocale = setlocale(LC_TIME, 'en_US');
echo strftime("%a %d %b %Y", strtotime($jitem1->publish_up));
setlocale(LC_TIME, $oldLocale);
?>
</div>
<div><?php echo $jitem1->fulltext; ?></div>
</li>
<?php endforeach; ?>
However I would like to sort the foreach function by date, I have tried two different way of doing it (based on other SE questions) but each time I get this warning:
Warning: usort() expects parameter 1 to be array, null given in...
Here is my first try:
$jfeed1= $jdb1->loadObjectList();
function date_compare($a, $b)
{
$t1 = strtotime($a['publish_up']);
$t2 = strtotime($a['publish_up']);
return $t1 - $t2;
}
usort($jitem1, 'date_compare');
foreach ($jfeed1 as $jitem1):
And here was my second try:
$jfeed1= $jdb1->loadObjectList();
usort($jfeed1->publish_up, function($a, $b) {
$date1 = DateTime::createFromFormat('Y-m-d H:i:s', $a);
$date2 = DateTime::createFromFormat('Y-m-d H:i:s', $b);
return $date1 > $date2;
});
foreach ($jfeed1 as $jitem1):
I've "learned" php just by looking at codes and tuto, so I am missing a lot of fondamental notions that why I don't understand what I am supposed to do to solve this warning. Thanks for your help!
EDIT 1: The function
<?php
var_dump($jfeed1)
?>
gives me for the first item:
array(22) { [0]=> object(stdClass)#318 (5) { ["fulltext"]=> string(212) "Yesterday ..." ["alias"]=> string(3) "237" ["metakey"]=> string(7) "Romania" ["publish_up"]=> string(19) "2011-11-15 09:06:39" }
EDIT 2
$jfeed1= $jdb1->loadObjectList();
function date_compare($a, $b)
{
$t1 = strtotime($a['publish_up']);
$t2 = strtotime($b['publish_up']);
return $t1 - $t2;
}
usort($jfeed1, 'date_compare');
foreach ($jfeed1 as $jitem1):
You can sort out each array entry by the date directly in the query with:
ORDER BY publish_up DESC (descending order)
ORDER BY publish_up ASC (ascending order)
As in:
$jquery1 = "SELECT `fulltext`,alias,metakey,publish_up,metadesc FROM xxx_content WHERE catid=22 AND state= '1' ORDER BY publish_up ASC";
If you want to keep this PHP function date_compare
then you have to replace:
$a['publish_up']
by
$a->publish_up
As in:
$jfeed1= $jdb1->loadObjectList();
function date_compare($a, $b)
{
$t1 = strtotime($a->publish_up);
$t2 = strtotime($b->publish_up);
return $t1 - $t2;
}
usort($jfeed1, 'date_compare');
foreach ($jfeed1 as $jitem1):
return $t1 - $t2;
is ascending
return $t2 - $t1;
is descending