1

I have an array of news like

Array
(
  [0] => Array
    (
        [news_published] => 1337192831
        [news_category] => 5
    )

  [1] => Array
    (
        [news_published] => 1334566743
        [news_category] => 5
    )

  [2] => Array
    (
        [news_published] => 1340092425
        [news_category] => 6
    )

  [3] => Array
    (
        [news_published] => 1339740173
        [news_category] => 6
    )

  [4] => Array
    (
        [news_published] => 1336148837
        [news_category] => 6
    )
)

How I can sort news_published by descending order....I have tried with 'usort' but cant find the result properly can anyone suggest me?

Ahmed Syed
  • 1,179
  • 2
  • 18
  • 44
GautamD31
  • 28,552
  • 10
  • 64
  • 85

3 Answers3

10

Try this :

$arr  = your array;
$sort = array();
foreach($arr as $k=>$v) {
    $sort['news_published'][$k] = $v['news_published'];
}

array_multisort($sort['news_published'], SORT_DESC, $arr);

echo "<pre>";
print_r($arr);
Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
0
<?php


 $array = array( array('news_published'=>'1337192831','news_category'=>'5'),
            array('news_published'=>'1337192231','news_category'=>'5'),                
            array('news_published'=>'1337192921','news_category'=>'6'),

           );
  / orignal array
 print_r($array);

foreach ($array as $key => $row) {
$new_published[$key] = $row['news_published'];
 }
array_multisort($new_published, SORT_DESC,$array);

 // sorted array
print_r($array);

 ?>
alwaysLearn
  • 6,882
  • 7
  • 39
  • 67
0

Or this:

function sortForMe($a, $b)
{
    if ((int)$a['news_published'] === (int)$b['news_published']) {
        return 0;
    }
    return (int)$a['news_published'] < (int)$b['news_published'] ? -1 : 1;
}

usort($array, 'sortForMe');

you can use function or static method from class - your choice :)

mkjasinski
  • 3,115
  • 2
  • 22
  • 21