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 に答える