0

我目前有一个这样的数组(问题中的所有数组都是 JSON 格式):

{
    "array":[
        "item",
        "item2",
        "item3"

       //etc..

    ]
}

我将一个数组添加到这个数组中['array'][] = array("x"=>"y","z"=>"a");

现在我的数组看起来像这样:

{
    "array":{
        "0":"item",
        "1":"item2",
        "2":"item3",
        "newItem": {
            "x":"y",
            "z":"a"
        }

       //etc..

    }
}

如何从数组中删除“0”和“1”,所以我只有这个?:

{
    "array":[
        "item",
        "item2",
        "item3",
        "newItem": {
            "x":"y",
            "z":"a"
        }

       //etc..

    ]
}
4

2 回答 2

3

So let's take your original JSON as input

{
    "array":[
        "item",
        "item2",
        "item3"
    ]
}

You can use json_decode() to convert the JSON data to PHP. Judging from your array modification code you want to provide true as the second argument to json_decode()

$data = json_decode("{\"array\":[\"item\",\"item2\",\"item3\"]}", true);

You can then add data

$data['array'][] = array("x"=>"y","z"=>"a");

Now, you can use json_encode() to convert the PHP data to JSON again

echo json_encode($data);

This will print

{
    "array":[
        "item",
        "item2",
        "item3",
        {
            "x":"y",
            "z":"a"
        }
    ]
}

You can alternatively pass JSON_FORCE_OBJECT as the second argument to json_encode() to force conversion of arrays to objects and thus the creation of keys

echo json_encode($data, JSON_FORCE_OBJECT);

This alternative call will print

{
    "array":{
        "0":"item",
        "1":"item2",
        "2":"item3",
        "3":{
            "x":"y",
            "z":"a"
        }
    }
}

Note, that the call without JSON_FORCE_OBJECT does not have the array indices, while your JSON data has them. The reason is in the different way you modify your data. You probably use the following code

$data['array']['newItem'] = array("x"=>"y","z"=>"a");

By providing a key for this new item it has to be represented as an object in JSON. The array now contains an object and all the other items are promoted to objects, too.

To fix your problem you should modify your data like so

$data['array'][] = array('newItem' => array("x"=>"y","z"=>"a"));

This will give you

{
    "array":[
        "item",
        "item2",
        "item3",
        {
            "newItem":{
                "x":"y",
                "z":"a"
            }
        }
    ]
}
于 2013-10-05T00:45:00.960 回答
0

我不认为你可以有一个没有键的 PHP 数组,我认为你不能有没有键的 JSON。如果您不指定它们,PHP 将始终添加键http://php.net/manual/en/language.types.array.php

“我目前有这样的数组”是什么意思?你的 JSON 看起来像这样吗?它有效吗?

于 2013-10-05T00:18:33.687 回答