php - 致命错误:未捕获的错误:不能在 C:\xampp\htdocs\MyShoppingList\list.php:487 中使用 stdClass 类型的对象作为数组
问题描述
当我运行代码时,我收到错误:
致命错误:未捕获的错误:不能在 C:\xampp\htdocs\MyShoppingList\list.php 中使用 stdClass 类型的对象作为数组:487 堆栈跟踪:#0 {main} 在 C:\xampp\htdocs\MyShoppingList\list 中抛出。第 487 行的 php;
我不确定为什么?
function updateList() {
//? Retrieve items from form POST, decode & unserialize using json. Empty array if not available.
$items = $_POST['items']
? json_decode(base64_decode($_POST ['items'], true))
: [];
//? Check if food and category was supplied.
if(filter_input(INPUT_POST, 'food') !== "" && filter_input(INPUT_POST, 'category') !== "") {
//? Add food/category as item to Shopping List
$items[] = [
"food" => filter_input(INPUT_POST, 'food'),
"category" => filter_input(INPUT_POST, 'category'),
];
}
return $items;
}
<input type="hidden" name="items" value="<?php echo base64_encode(json_encode($items)) ?>">
<div id="table">
<table width="100%">
<?php if ($items) { ?>
<?php foreach($items as $item){?>
<tr>
<td id="dairy">
<?php echo $item['category'];?>
</td>
</tr>
<form>
<tr>
<td id="data">
<?php echo'';?>
<label class="container">
<input
id="<?php echo "check${k}"; ?>"
type="checkbox"
name="<?php echo "check${k}"; ?>"
value="<?php echo $item['food']; ?>">
<span class="checkmark"></span>
</label>
</td>
</tr>
</form>
<?php } ?>
<?php } else { ?>
<tr>
<td align="center" style="padding: 20px">No items in list.</td>
</tr>
<?php } ?>
</table>
解决方案
这是一个json_decode
问题:它应该有true
第二个参数才能得到数组的结果。在您的代码中,此函数使用一次,但没有第二个参数。
这意味着:而不是
json_decode(base64_decode($_POST ['items'], true))
它应该是:
json_decode(base64_decode($_POST ['items']), true)
或者,如果需要 base64_decode 的第二个参数:
json_decode(base64_decode($_POST ['items'], true), true)
推荐阅读
- python - python Django REST Framework CSRF 失败:未设置 CSRF cookie?
- javascript - useEffect 中的异步函数在组件渲染后获取数据
- javascript - 输入类型=“时间”中只有小时和分钟
- react-native - 当我获取数据时,我可以看到状态已设置,但是当我从状态调用数据时,它显示对象未定义
- c - 如何在C中将整数转换为带有前导零的字符串?
- excel - Excel VBA复制具有匹配单元格数据的数据列
- python - 仅在所有特定键上从 python 字典查询 Mongodb
- javascript - 使用 JavaScript/TypeScript 过滤两个数组
- python - 添加错误检查会使脚本陷入无限循环(python)
- c# - 在c#中是否有一种方法可以通过字符串转换子类的实例?