gpt4 book ai didi

php - JSON 到 PHP,然后是 foreach?

转载 作者:行者123 更新时间:2023-11-29 05:45:55 24 4
gpt4 key购买 nike

我从 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 数据吗?

最佳答案

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com