将对象数组保存到codeigniter中

时间:2013-12-23 09:28:27

标签: javascript php jquery arrays codeigniter

我构建了一个表单,我必须根据下面的输入类型创建对象数组,如下所示:

{
 "name_node":{"type":"input","name":"name","validation":"required, alpha numeric"},
 "content":{"type":"textarea","name":"contentco","validation":"required, alpha numeric"}
}

我使用Jquery构建此数组,然后将其保存到表单中名为“inputs”的隐藏输入字段。所以当我提交表格时,我可以检索上面的对象,如:

$this->input->post('inputs');

我需要做的是将以前的对象保存为以下格式

[inputs] => Array(
                  [name_node] => Array(
                        [type] => input
                        [slug] => name_node
                        [name] => name
                        [validation] => Array
                            (
                                [0] => required
                                [1] => alpha numeric
                            )

                    )

                [content] => Array
                    (
                        [type] => textarea
                        [slug] => content
                        [name] => content
                        [validation] => Array
                            (
                                [0] => required
                                [1] => alpha numeric
                            )

                    )

            )

2 个答案:

答案 0 :(得分:2)

您可以使用json_decode()在PHP中实现,并使用foreach循环格式化您的数组。

$str = '{
"name_node":{"type":"input","name":"name","validation":"required, alpha numeric"},
"content":{"type":"textarea","name":"contentco","validation":"required, alpha numeric"}
}';

$arr = json_decode(($str), true);

foreach ($arr as $k => $v) {
   $newArray[$k] = $v;
   $newArray[$k]['slug'] = $k;
   if(isset($v['validation'])) {
     $newArray[$k]['validation'] = explode(",",$v['validation']);
   }

}
print_r($newArray);

Working Demo

答案 1 :(得分:0)

$inputs = json_decode($this->input->post('inputs'));

现在,如果你print_r($inputs);,你会得到吼叫形成

 stdClass Object
    (
        [name_node] => stdClass Object
            (
                [type] => input
                [name] => name
                [validation] => required, alpha numeric
            )

        [content] => stdClass Object
            (
                [type] => textarea
                [name] => contentco
                [validation] => required, alpha numeric
            )

    )

如果你想要精确的结构......

$inputs_object = json_decode($this->input->post('inputs'));

$data['inputs'] = array(
                        'name_node'=>(array)$inputs_object ->name_node,
                        'content'=>(array)$inputs_object ->content,
                    )

$data['inputs']['name_node']= explode(',',$data['inputs']['name_node']['validation']);
$data['inputs']['content']= explode(',',$data['inputs']['content']['validation'])