为什么要向该阵列添加新的阵列对象?

时间:2019-02-10 20:22:29

标签: php arrays

我正在尝试使用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);

wich结果为:

[
    [
        [
            {"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"}
]

1 个答案:

答案 0 :(得分:1)

[]变量的末尾$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);
?>

哪个输出:

[{"item":"vla","amount":"3","shop":"Albert hijen"},{"item":"item02","amount":"4","shop":"Workshop 01"}]

您可以在https://ideone.com/MHmmTX上进行实时测试