

新闻资讯
技术学院本文详解 php 中多维关联数组的遍历、字段提取与数据库插入操作,重点纠正对象访问语法错误(如 `$arr->key`)、解决“illegal string offset”和“t
rying to get property of non-object”等常见报错,并提供安全、可扩展的插入方案。
在 PHP 开发中,将多维数组(尤其是由查询结果生成的关联数组)持久化到数据库是高频需求。但初学者常因混淆数组语法与对象语法而报错——如 Trying to get property of non-object 或 Illegal string offset。根本原因在于:你提供的 $output_querys 是一个索引数组,其每个元素是关联数组(array),而非对象(stdClass 或自定义类实例),因此必须使用 $output_query['ID'],而非 $output_query->ID。
foreach ($output_querys as $output_query) {
// ✅ 正确:关联数组用 [] 访问键
$Pv_ID = $output_query['ID'];
$Pv_Code = $output_query['Code'];
$Pv_Description = $output_query['Des'];
// 构建待插入数据(键名需与数据库字段严格对应)
$data_final = [
'id' => $Pv_ID,
'code' => $Pv_Code,
'des' => $Pv_Description
];
// ⚠️ 关键:insert 必须在循环内调用,否则只插入最后一组数据
$db->insert('abc', $data_final); // 注意表名 'abc' 应为字符串(加引号)
}| 错误代码 | 问题原因 | 修正方式 |
|---|---|---|
| $output_query->ID | 尝试以对象方式访问数组,触发 Trying to get property of non-object | 改为 $output_query['ID'] |
| id => $Pv_ID(未加引号) | PHP 将 id 解析为常量(未定义则转为空字符串),导致字段名错误 | 写为 'id' => $Pv_ID |
| db->insert(abc, ...) | 表名 abc 缺少引号,被当作常量或未定义标识符 | 改为 'abc'(字符串) |
若数据量较大,逐条 INSERT 效率低。推荐使用 PDO 的预处理批量插入(更安全高效):
try {
$pdo = new PDO($dsn, $user, $pass);
$stmt = $pdo->prepare("INSERT INTO abc (id, code, des) VALUES (?, ?, ?)");
foreach ($output_querys as $row) {
$stmt->execute([
(int)$row['ID'], // 强制类型转换,防注入
trim($row['Code']), // 清理空格
trim($row['Des'])
]);
}
echo "✅ 成功插入 " . count($output_querys) . " 条记录";
} catch (PDOException $e) {
error_log("DB Insert Error: " . $e->getMessage());
throw new Exception("数据库写入失败,请检查日志");
}掌握数组访问语法与数据库操作的语义匹配,是 PHP 数据处理的基石。遵循上述规范,即可稳定、安全地完成多维数组入库任务。