0

When I did

$result = array_count_values(Visitor::all()->pluck('device')->toArray());
$result = asort($result,SORT_NATURAL);
return $result;

I kept getting

The Response content must be a string or object implementing __toString(), "boolean" given.

enter image description here

This is an array

array_count_values(Visitor::all()->pluck('device')->toArray())

It returns

{
    iPhone: 202,
    Windows NT 6.1: 2428,
    Windows NT 10.0: 2588,
    Macintosh: 1397,
    iPad: 12,
    Windows NT 6.2: 50,
    Windows NT 6.3: 90,
    X11: 442,
    compatible: 1813,
    Windows NT 5.1: 97,
    Linux: 227,
    Windows: 86,
    TweetmemeBot/4.0: 8,
    ) { :: 14,
    Windows NT 6.0: 7,
    User-Agent,Mozilla/5.0 : 1,
    KHTML, like Gecko: 6,
    Unknown: 11,
    Android: 1,
    Android 7.1.1: 1,
    Android 7.1.2: 2,
    Windows NT x.y: 2,
    Windows NT 6.1) AppleWebKit/537.36 : 7,
    Windows NT 5.0: 1,
    Windows NT 8.0: 1,
    web crawler :: robots.txt exclude elefent: 1,
    Windows NT: 1,
    Linux 4.4.0-116-generic: 1
}

I want to sort them in a desc base on values.

Please help

3
  • asort() sorts the array in place, no need to resassign Commented Sep 11, 2019 at 15:02
  • @axiac : please remove your downvote. I added texts now. Commented Sep 11, 2019 at 15:14
  • @BrettGregson : How do I do it on a DESC order ? Commented Sep 11, 2019 at 15:24

3 Answers 3

1

asort() returns a boolean indicating whether the operation was successful or not. What you want to do instead is this :

$result = array_count_values(Visitor::all()->pluck('device')->toArray());
asort($result,SORT_NATURAL);

return $result;

See the documentation for more information

Sign up to request clarification or add additional context in comments.

1 Comment

How do I do it on a DESC order ?
1

asort returns a boolean indicating if the sort was managed ok or not. It sorts the array by reference.

Change your code to:

$result = array_count_values(Visitor::all()->pluck('device')->toArray());
asort($result,SORT_NATURAL);
//$result is now sorted.
return $result;

1 Comment

How do I do it on a DESC order ?
1

asort() does not return the sorted array but a boolean to say if it's done (true) or not (false)

$result = array_count_values(Visitor::all()->pluck('device')->toArray());
asort($result, SORT_NATURAL);
return $result;

2 Comments

How do I do it on a DESC order ?
Use arsort(). It does the same as asort() but in reverse order.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.