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?

4

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

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);

 ?>

Comments

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 :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.