0

我需要帮助来抑制我从foreach()

Warning: Invalid argument supplied for foreach() in 
/sitename/pages/admin/questions/index.php

我得到了我想要的结果。我只需要删除警告...

这是我的代码:

for($i = 1; $i <= $RESULTS_count; $i++){

$rawResult = $wpdb->get_row(
                $wpdb->prepare("SELECT * FROM ".WPSQT_TABLE_RESULTS." WHERE id = $i"),ARRAY_A);

$rawResult['sections'] = unserialize($rawResult['sections']);

     foreach($rawResult['sections'] as $result_sections){
         if($result_sections['answers'][1]['mark'] == 'correct') $correct_answer++;
    }
}
echo $correct_answer/$RESULTS_count;

如果我将代码从 FOR 循环中取出并替换WHERE id = $iWHERE id = 1它将起作用......问题可能是 FOREACH 不喜欢处于 FOR 循环中吗?

你觉得我应该怎么做?

编辑:我认为我收到的警告是由于我删除了 ID 为 2 的结果,因此当循环遍历表行时,其中一个为空,这就是我收到警告的方式...

4

1 回答 1

4

您应该首先确保数据是一个数组或将其类型转换为一个数组。

是数组:

    if (is_array($rawResult['sections'])) {
        foreach ($rawResult['sections'] as $result_sections) {
            if ($result_sections['answers'][1]['mark'] == 'correct')
                $correct_answer++;
        }
    }

类型转换:

    foreach ( (array) $rawResult['sections'] as $result_sections) {
        if ($result_sections['answers'][1]['mark'] == 'correct')
            $correct_answer++;
    }
于 2012-07-13T16:07:09.550 回答