如何使用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?

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