如何修复PHP数组赋值时的Illegal offset type错误?
解决PHP数组匹配时的Illegal offset type错误
尝试在两个数组中根据post_id匹配,将对应post的标题赋值到目标数组,但出现错误:
致命错误:未捕获的TypeError: Illegal offset type,错误行位于$array[$week][$days][$day]['post_title'] = $post_data['post_title'];
错误原因
$week和$days是数组对象,而非数组键名,PHP不允许用数组作为数组索引,这是报错核心。- 原代码中
$array是JSON字符串,未转换为PHP数组,is_array($array)返回false,函数直接返回false。 $posts定义存在语法错误,缺少闭合括号。- 多层嵌套循环效率低下,每次匹配都需遍历全部posts。
解决方案
- 修正语法与格式错误:补全
$posts的闭合括号,将JSON格式的$array转换为PHP数组。 - 循环时保留键名:遍历数组时同时获取键名和值,使用键名操作数组索引。
- 优化匹配逻辑:将
$posts转换为以post_id为键的关联数组,直接通过键名匹配,避免冗余循环。
修正后的完整代码
<?php // 修正语法错误,规范数组写法 $posts = [ ['post_id' => 3, 'post_title' => 'Task 1'] ]; // 将JSON字符串转为PHP关联数组 $jsonArray = '[{"week1":{"day1":[{"post_id":"3","post_type":"timebased","post_reps":"","post_sets":"","post_time":"60","post_rest":"30"},{"post_id":"2","post_type":"repsbased","post_reps":"12","post_sets":"4","post_time":"","post_rest":"35"}],"day2":[{"post_id":"1","post_type":"repsbased","post_reps":"8","post_sets":"4","post_time":"","post_rest":"30"},{"post_id":"2","post_type":"repsbased","post_reps":"8","post_sets":"5","post_time":"","post_rest":"60"}],"day3":[],"day4":[],"day5":[],"day6":[],"day7":[]}}]'; $array = json_decode($jsonArray, true); function getTitle($array, $posts) { if (!is_array($array)) { return false; } // 构建post_id到post_title的映射,提升匹配效率 $postMap = []; foreach ($posts as $post) { $postMap[(string)$post['post_id']] = $post['post_title']; } // 遍历周数据,保留键名 foreach ($array as $weekKey => $week) { // 遍历天数据,保留键名 foreach ($week as $dayKey => $dayPosts) { // 遍历当天的所有帖子 foreach ($dayPosts as $index => $postData) { $postId = $postData['post_id']; // 存在对应标题则赋值 if (isset($postMap[$postId])) { $array[$weekKey][$dayKey][$index]['post_title'] = $postMap[$postId]; } } } } return $array; } // 调用函数并输出结果 $result = getTitle($array, $posts); print_r($result); ?>
关键修改说明
- 规范
$posts的数组写法,修复语法错误。 - 使用
json_decode($jsonArray, true)将JSON字符串转为可操作的PHP关联数组。 - 构建
$postMap映射表,将匹配操作的时间复杂度从O(n*m)优化为O(n)。 - 循环时使用
$weekKey、$dayKey、$index作为数组索引,避免用数组对象作为索引的错误。
内容的提问来源于stack exchange,提问作者bdroid
相关产品推荐
相关产品推荐

