douduonang3169 2019-07-09 19:57
浏览 368

如何使用PHP中的foreach循环解决'notice:array to string conversion'错误?

I want to show 10 questions options using PHP and MySQL, and show each question options using foreach loop, but I get a notice.

I have 2 tables named "questions" and "options" and I have a field in options named q_id which has joined question table by id field.

This is my SQL code:

public function selectOptions($id)
{
    $sql = $this->pdo->prepare("select options.option1,options.option2,options.option3,options.option4 FROM `options` INNER JOIN questions ON options.q_id = questions.id WHERE questions.id = '$id'");
    $sql->execute();
    $row = $sql->fetchAll(PDO::FETCH_ASSOC);
    //var_dump($row);die;
    return $row;
}

and this is my PHP code:

foreach ($num as $key => $value) {
    $toal[] = $num[$key]->id;//this will be the questions id
}

$q_id = $toal;

foreach ($q_id as $val) {
    $j =$obj->selectOptions($q_id);//this will select options
    var_dump($j);
}

I expect the output to be an array of options but it returns an error:

notice : array to string conversion

How can I resolve the above issue?

  • 写回答

1条回答 默认 最新

  • douzhanglun4482 2019-07-09 20:05
    关注

    You sending the wrong argument to the function as you sending $q_id (the original array) and not $val.

    Your code say:

    foreach ($q_id as $val) {
        $j =$obj->selectOptions($q_id); // you use the $q_id which is array
    

    The selectOptions is treating its argument as string and not array therefor the notice.

    Change your code to:

    foreach ($q_id as $val) {
        $j =$obj->selectOptions($val);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?