为什么一个新的Array对象添加到这个阵列?

问题描述 投票:0回答:1

我试图使用PHP项目添加到一个JSON数组但是当我运行的代码(下)的新的数组对象添加的,而不是一个常规的对象。有人可以清除此为我?我是很新的PHP和googleling没有解决这个问题对我来说。

// Get data from cache
$cache_data = file_get_contents('shoppinglist.json');
$cache[] = json_decode($cache_data, true);

// Get data from url and parse it to an object
$data->item = $_GET['item'];
$data->amount = $_GET['amount'];
$data->shop = $_GET['shop'];

// Combine cache and data item
array_push($cache, $data);

// Write to shopping list file
$fp = fopen('shoppinglist.json', 'w');
fwrite($fp, json_encode($cache));
fclose($fp);

至极导致:

[
    [
        [
            {"item":"vla","amount":"3","shop":"Albert hijen"},
            {"item":"vla","amount":"3","shop":"Albert hijen"}
        ],
        {"item":"vla","amount":"3","shop":"Albert hijen"}
    ],
    {"item":"vla","amount":"3","shop":"Albert hijen"}
]
php arrays
1个回答
1
投票

在qazxsw POI变量赋值后qazxsw POI要强制包装阵列的创建。有一次,删除,代码应该按预期工作,如下面的例子:

[]

其输出:

$cache

您可以测试这个活在<?php $cache_data = '[{"item":"vla","amount":"3","shop":"Albert hijen"}]'; $cache = json_decode($cache_data, true); $mapNewItem = array("item"=>"item02", "amount"=>"4", "shop"=>"Workshop 01"); array_push($cache, $mapNewItem); echo json_encode($cache); ?>

© www.soinside.com 2019 - 2024. All rights reserved.