如何从Mysql中获取json数据并将其转换为CodeIgniter中的数组

时间:2016-10-06 07:22:44

标签: php mysql arrays json codeigniter

我已经获得了以下格式的MySQL结果。我想在app中将其作为JSON数组格式发送。关键字数据在db中以JSON数组格式存储。如何将此作为JSON数组发送?

MySQL结果

Array 
(
    [groups] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 7
                    [category_name] => Serial
                    [group_name] => test group
                    [description] => efrt
                    [image] => 9955_1475731912.png
                    [time] => 07:30 AM
                    [member_count] => 0
                    [keyword] => [{"key_id":"1","key_name":"HBO"},
                                 {"key_id":"2","key_name":"BOLLYWOOD HUNGAMA"},
                                 {"key_id":"3","key_name":"SERIALS"}]
                )

        )

        "member_count": "0"
    }]
}

JSON编码格式

{
  "groups": [
    {
      "id": "7",
      "category_name": "Serial",
      "group_name": "test group",
      "description": "efrt",
      "image": "9955_1475731912.png",
      "time": "07:30 AM",
      "member_count": "0",
      "keyword": "[{\"key_id\":\"1\",\"key_name\":\"HBO\"},
                  {\"key_id\":\"2\",\"key_name\":\"BOLLYWOOD HUNGAMA\"},
                  {\"key_id\":\"3\",\"key_name\":\"SERIALS\"}]"
    }
  ]
}

3 个答案:

答案 0 :(得分:1)

首先以你想要在函数内部编码的方式创建一个php数组 或使用以下样本 在模型中(扩展CI_Model)

$query_result = $result->result(); //for get result array 
return json_encode($query_result);

样品

    $array = array("test"=>"hhh",array("us"=>"letter","test"=>"ttt"));
    //print_r(json_encode($array));
    return json_encode($array);

答案 1 :(得分:0)

我将此方法用于我的问题

    foreach ($result['groups'] as $key ) {
                $json = $key->keyword;
                $keys = json_decode($json);
                $arrayName = array();
                foreach ($keys as $value) {
                     $key_id = $value->key_id;
                     $key_name = $value->key_name;
                     $arrayName[] = array('key_id' =>$key_id ,'key_name'              =>$key_name);
                }
    $key->keyword =  $arrayName;
 }
 $result['success']= 1; 
 echo json_encode($result);
 exit();

答案 2 :(得分:0)

$this->output
    ->set_content_type('application/json')
    ->set_output(json_encode($result->result()->groups));

我认为这会解决它