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条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀