0

my array have this structure:

$news = array('id' => '', 'views' => '');

i need to order this by the most viewed, but it have to match the id. I've done some research but got many doubts.

Orangepill
  • 23,853
  • 3
  • 38
  • 62
N. Reek.
  • 47
  • 5

1 Answers1

1

I'm having some trouble deciphering exactly what you mean with the question but here a couple of thinks that may work for you.

if your array is composed like

array(
      array("id"=>1, "views"=>50),
      array("id"=>3, "views"=>16)
);

Then you can use usort with a closure(php 5.3)

usort($news, function ($a, $b){ return $a["views"] - $b["views"]});

if you want it in descending order you can just swap the $a and $b in the closure

usort($news, function ($a, $b){ return $b["views"] - $a["views"]});

If you have an array that is composed like

array(
     "id"=>array(1,2),
     "views"=>array(50, 16)
);

Then you can use array_multisort

array_multisort($news["views"], $news["id"]);

or if you want it in descending order

array_multisort($news["views"], SORT_DESC, SORT_NUMERIC, $news["id"]);

UPDATE

The final solution.. news was an object with a views and id array properties. The final solution was:

array_multisort($news->views, $news->id);
Orangepill
  • 23,853
  • 3
  • 38
  • 62
  • it returns: usort() expects parameter 1 to be array, object given – N. Reek. Jul 16 '13 at 22:02
  • i have the first case, but it returns the error "usort() expects parameter 1 to be array, object given". And i'm sorry for my confuse question, thats because i'm not a native english speaker :/ – N. Reek. Jul 16 '13 at 22:08
  • news isn't an array then... you might be able to cast it to one by using `(array)$news` – Orangepill Jul 16 '13 at 22:08
  • another error, it says "undefined index views". The print_r of the array return this structure (and thanks for being patient): Array ( [id] => Array ( [0] => 283 [1] => 284 [2] => 305 ) [views] => Array ( [0] => 73 [1] => 37255 [2] => 219827 ) ) – N. Reek. Jul 16 '13 at 22:20
  • try this `array_multisort($news->views, $news->id);` – Orangepill Jul 16 '13 at 22:24
  • It worked!!!!!! Thank you very much :D (now i realize how dumb i've been hahaha) – N. Reek. Jul 16 '13 at 22:26