我收到错误在下面的代码中为foreach()提供的无效参数。谁能告诉我这里做错了什么?我想在这里访问子数组值[0]和[1]。只是提到我现在不知道很多值将在子数组中。
我在违规代码行(错误所在的位置)上面发表了评论
echo "<pre>";
print_r($mySessData);
echo "</pre>";
Array
(
[addtypeid] =>
[isnew] =>
[orderby] =>
[geographicareaid] =>
[catid] => 1
[catid2] =>
[manufacturerid] =>
[modelid] =>
[yearofmanufacturing_from] =>
[yearofmanufacturing_to] =>
[hoursused_from] =>
[hoursused_to] =>
[horsepowers_from] =>
[horsepowers_to] =>
[price_from] =>
[price_to] =>
[colorid] =>
[isdamaged] =>
[categoriesfilters] =>
Array
(
[0] => 67
[1] => 158
)
)
$sessData = array();
$myresult = array();
$val = array();
if (!empty($mySessData)){
foreach ($mySessData as $sessData) {
// the line bellow is the offending line, where the error is thrown
foreach ($sessData as $val) {
$myresult[$val]= $val;
foreach($filters as $f) {
if ($f['filterid'] == $myresult[$val]) {
$strWhere2 .= $myresult[$val] .",";
} // end if
} // end of third foreach
} // end of second foreach
} // end of first foreach
} // end if
答案 0 :(得分:1)
那是因为你没有检查$sessData
实际上是否是一个数组。实际上,只有一个案例中的数组正在查看您的转储。只需添加另一个if (is_array($sessData))
答案 1 :(得分:1)
在循环之前,您需要检查您的值是否是实际数组。当前数组的唯一值是[categories filters]
答案 2 :(得分:0)
这个变量$sessData
可能会从更大的循环中变空
并循环遍历它,在PHP&lt; = 5.3中它将会中断:
答案 3 :(得分:0)
您有一个“简单数组”,并尝试将其作为多维数组处理。
您可能希望使用foreach($mySessData as $key => $val)
填充变量$myresult
,并使用if (is_array($val))
来处理categoriesFilter键。
我不知道你到底需要什么,但这可能会对你有所帮助:
$myresult = array();
if (!empty($mySessData)){
foreach ($mySessData as $key => $val) {
// the line bellow is the offending line, where the error is thrown
$myresult[$val]= $val;
}
// I don't know what filters refers to, but I suppose you have to do something like this:
$strWhere2 = '';
foreach($filters as $f) {
foreach($myresult['categoriesFilter'] as $categ_filter)
if ($f['filterid'] == $categ_filter) {
$strWhere2 .= $categ_filter .",";
}
} // end if