只有变量应该通过引用传递 - Laravel 5

Only variables should be passed by reference - Laravel 5

我做的时候

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

我一直在

Only variables should be passed by reference

这是一个数组

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

它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
}

我想根据 array_count_values 对它们进行降序排序。

为什么会出现该错误?

asort() 需要一个数组参数变量(不是像 toArray() 这样的函数的结果)。此函数修改数组本身(不返回排序后的数组),成功时 returns true 或错误时 false

asort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) : bool

只需将结果分配给 $variable,然后使用 asort($variable) 或任何其他带有 &$array 参数的数组排序函数(由 reference)

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

SORT_NATURAL 标志对您的情况应该有用。我正在考虑 pluck 返回你的数据,因为我必须排序。

arsort($arr,SORT_NATURAL);
// I suggest you write this in separate line because it  
// Returns TRUE on success or FALSE on failure which I don't think you want.
// Please see https://www.php.net/manual/en/function.arsort.php
return $arr; 

Note:- SORT_NATURAL - compare items as strings using "natural ordering" like natsort()

输出:-

Array
(
    [Windows NT 10.0] => 2588
    [Windows NT 6.1] => 2428
    [compatible] => 1813
    [Macintosh] => 1397
    [X11] => 442
    [Linux] => 227
    [iPhone] => 202
    [Windows NT 5.1] => 97
    [Windows NT 6.3] => 90
    [Windows] => 86
    [Windows NT 6.2] => 50
    [) { :] => 14
    [iPad] => 12
    [Unknown] => 11
    [TweetmemeBot/4.0] => 8
    [Windows NT 6.1) AppleWebKit/537.36 ] => 7
    [Windows NT 6.0] => 7
    [KHTML, like Gecko] => 6
    [Android 7.1.2] => 2
    [Windows NT x.y] => 2
    [Android] => 1
    [Android 7.1.1] => 1
    [User-Agent,Mozilla/5.0 ] => 1
    [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
)

Demo.

编辑

$data = Visitor::all()->pluck('device')->toArray();
$retArr = array_count_values($data);
arsort($retArr,SORT_NATURAL);
return $retArr;