如何删除元素数组" [" &安培; "]"在json?

时间:2014-10-17 10:37:20

标签: javascript php json yii

我已经拥有变量JSON编码,然后在json数组中有像#34; ["和"]"。问题是?如何删除元素。

这是改变之前的json的一个例子

[{
    "form": {
        "user_id": "1",
        "form_id": 26,
        "form_name": "KireniuS",
        "form_description": "afafasf",
        "form_json": [{
            "id": 72043,
            "name": "EditText",
            "input_type": "text",
            "hint": "",
            "options": ""
        }, {
            "id": "409289",
            "name": "Ini Spinner",
            "input_type": "spinner",
            "hint": "ini saya ro",
            "options": "Saya, dan Dia"
        }],
        "created_at": "17-10-2014_16:49",
        "created_by": "adminweb",
        "last_updated_at": "17-10-2014_16:49"
    }
}]

PHP:

$jadi_json = array();
        foreach($model as $row)
        {
            $json_converter = json_decode($row->json_form);


            $saya = array(
                "form"=>array(
                    "user_id"=>$row->id_user,
                    "form_id"=>$row->id_form,
                    "form_name"=>$row->form_name,
                    "form_description"=>$row->form_description,
                    "form_json"=>$json_converter->form_json,
                    "created_at"=>$row->created_at,
                    "created_by"=>$row->created_by,
                    "last_updated_at"=>$row->last_updated_at
                ));
            array_push($jadi_json, $saya);
        }
        header('Content-Type: application/json');
        echo json_encode($jadi_json);

希望json格式

{
    "form": {
        "user_id": "1",
            "form_id": 26,
            "form_name": "KireniuS",
            "form_description": "afafasf",
            "form_json": [{
            "id": 72043,
                "name": "EditText",
                "input_type": "text",
                "hint": "",
                "options": ""
        }, {
            "id": "409289",
                "name": "Ini Spinner",
                "input_type": "spinner",
                "hint": "ini saya ro",
                "options": "Saya, dan Dia"
        }],
            "created_at": "17-10-2014_16:49",
            "created_by": "adminweb",
            "last_updated_at": "17-10-2014_16:49"
    }
}

元素数组" ["和"]"只是表面上省略。

1 个答案:

答案 0 :(得分:1)

首先,您的JSON位于表单对象列表中。要解析JSON,请使用json_decode($json)CJSON::decode($json)。你将有这样的数组:

 array(
     0 => array('form' => array(...)),
     // if there is any more `form` elements:
     1 => array('form' => array(...)),
 );

要从数组中获取第一个元素,请使用$myArray[0]current($myArray)(如果您不知道首先是哪个键)。

最后:

$myArray = CJSON::decode($row->json_form);
$saya = current($myArray);
$secondSaya = next($myArray);
$lastSaya = end($myArray);

如果您可以控制JSON的来源,请尝试更改它,因此它是单个条目而不是数组。 (例如CJSON::encode(array('form' => array('user_id' => 1, /*...*/)))