我从 jQueryscript 向我的 PHP 页面发送一个有效的 JSON 字符串:
var data = '{
"data":[
{
"id":"12",
"checked":"true"
},{
"id":"4",
"checked":"false"
},{
"id":"33",
"checked":"false"
}
]
}';
$.post ("page.php", { data_input:data }, function (data) {
// code
});
在我的 PHP 页面中获取数据后,我使用 json_decode
方法解析它,然后尝试在为 创建的
查询:foreach
语句中使用它>PDO
<?php
$data_input = json_decode ($_REQUEST['data_input'], true);
$sql = "UPDATE my_table SET user_enabled = :checked WHERE node_prop_id = :id";
$stmt = $dns->prepare ($sql);
foreach ($data_input as $data) {
$ok = $stmt->execute ($data);
$num = $stmt->rowCount ();
}
if ($ok) return 1;
else return 0;
?>
这会返回错误:
PHP Warning: Invalid argument supplied for foreach() in /home/.../page.php on line XX
我能找到一种方法在 foreach
语句中使用我的 JSON 数据吗?
最佳答案
- 通过检查
json_last_error()
确保 json_decode 运行通过 - 确保检查
$data_input
是一个数组。 json_decode() 操作的结果是 not necessarily always an array :
Return value
Returns the value encoded in json in appropriate PHP type. Values true, false and null (case-insensitive) are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
虽然在你的情况下,它应该是。我打赌解码错误。
Edit: Victor Nicollet spotted the actual error. It's still good to use json_last_error and do some more checks!
关于php - JSON 到 PHP,然后是 foreach?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2073408/