首页 > 解决方案 > 致命错误:未捕获的错误:不能在 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>

标签: phpjson

解决方案


这是一个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)

推荐阅读