-1

I have some comments from customers, and I want to sort them by popularity. I can put them in an array to count each comment, but I want to order the comments by said count, how is this achieved?

I can make the arrays like this:

$arr['comment1'] = 4;
$arr['comment2'] = 2;
$arr['comment3'] = 6;

Or

$arr[] = array('comment'=>'comment1','count'=>4);
$arr[] = array('comment'=>'comment2','count'=>2);
$arr[] = array('comment'=>'comment3','count'=>6);

So I would like to re-order the array into this order - comment3, comment1, comment2 - i.e. in order of count. Is this possible?

Source
  • 998
  • 2
  • 9
  • 19
  • Use php's [usort](https://www.php.net/manual/en/function.usort.php), with a good sof example [here](https://stackoverflow.com/a/2699159/546262). – ehymel Jun 07 '19 at 01:11

1 Answers1

1

You probably need asort() or arsort(). This will sort the array while keeping the keys with the proper values.

Ascending: $sorted = asort($arr);

Descending: $sorted = arsort($arr);

Brack
  • 312
  • 2
  • 13