我正在一些旧的PHP网站上工作,无法弄清楚如何解决这种错误:
致命错误:未捕获错误:无法将字符串偏移量用作数组
这是引发错误的部分
$ret["content"]["news"] = array();
$start = ($pagenum - 1) * $page_rows;
$stop = ($count > $start + $page_rows) ? $start + $page_rows : $count;
for($i = $start; $i < $stop; $i++)
{
$cnt = sizeof($ret["content"]["news"]);
print_r($ret);
$ret["content"]["news"][$cnt] = $this->getPost($all[$i]);
}
print_r
返回
Array([content] => A [template] => intro)
此行引发错误
$ret["content"]["news"][$cnt] = $this->getPost($all[$i]);
答案 0 :(得分:1)
您的代码的许多部分都在交换您的变量。混合arrays
和strings
。请尝试以下方法:
for($i = $start; $i < $stop; $i++)
{
// Debug only. Remove once bugs are squashed.
if(!is_array($ret["content"])){
error_log("You've set ret['content'] as a non-array; probably a string!");
}
if(!is_array($ret["content"]["news"])){
error_log("You've set ret['content']['news'] as a non-array too!");
}
//end debug block
/***
* You do not need to count the array values each time, simply append with []
***/
$ret["content"]["news"][] = $this->getPost($all[$i]);
}