doujiang2641 2017-04-12 12:06
浏览 20
已采纳

严格标准错误,尝试将字符串反转为数组

So I have a string with comma separated values:

$accounts = "1,2,3,4,5,6";

And I want to reverse that order. So I wrote this:

$accountsrev = implode(',',rsort(explode(',',$accounts)));

Basically I convert to an array, reverse the array, and implode it back into a string. What's wrong with that?

I get a load of errors like this:

Strict Standards: Only variables should be passed by reference in /home/username/public_html/file.php on line 121

Warning: implode(): Invalid arguments passed in /home/username/public_html/file.php on line 121


Edit:

Now I wonder if the way I build the $accounts variable is wrong. I pull 7 rows from the database and then build the $accounts variable in a while loop. The id is an integer in the database:

$accounts = '';
$i = 1;
while ($data = $getdata->fetch(PDO::FETCH_ASSOC)) {
    if ($i < 7) {
        $accounts .= $data['id'].',';
    } else {
        $accounts .= $data['id'];
    }
    $i++;
}

Does the way I make the $accounts variable not produce a string?

  • 写回答

3条回答 默认 最新

  • dtewnsdf47253 2017-04-12 12:09
    关注

    This is just something that tells you you're doing something completely wrong:

    $array = [1,2,3,4];
    
    rsort($array);
    
    //$array is sorted. 
    

    However:

    rsort(array_filter($array)); 
    
    //Array filter returned a copy of the original array so $array is neither sorted nor filtered.
    

    You need to do:

    $accounts = '';
    while ($data = $getdata->fetch(PDO::FETCH_ASSOC)) {
        $accounts .= $data['id'].',';
    }
    $accountsrev = explode(',',rtrim($accounts,","));
    rsort($accountsrev);
    $accountsrev  = implode(',',$accountsrev);//accountsrev is sorted here
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?