php 为 foreach() 提供的参数无效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7490577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:47:31  来源:igfitidea点击:

Invalid argument supplied for foreach()

phparrayscodeigniterforeach

提问by Jennifer Anthony

How can fix error Message: Invalid argument supplied for foreach() - Line Number: 28in following foreach?

如何修复Message: Invalid argument supplied for foreach() - Line Number: 28以下错误foreach

<?php
$mileage = array();
$mileage_input = $this->input->post('mileage');
foreach ($mileage_input as $idx => $name) {  //Line 28
    $mileage[] = array(
        'mileage' => $mileage_input[$idx]
    );
}
$data = array(
    'mileage' => json_encode($mileage),
    'customer_number' => $customer_number,
    'name' => $this->input->post('name')
);
$this->db->insert('customer', $data);
?>

回答by Chris G.

$mileage_inputis probably not an array, which is why it isn't working.

$mileage_input可能不是数组,这就是它不起作用的原因。

回答by Alexander Olsson

Most likely $mileage_input is not an array. Perhaps you must error check $this->input->post.

很可能 $mileage_input 不是数组。也许您必须错误检查 $this->input->post。

If you dont really care about the error, but simply want to not get the error you can cast the value to an array before looping over it.

如果你真的不关心错误,只是不想得到错误,你可以在循环之前将值转换为数组。

foreach((array)$mileage_input as $idx => $name {