Miya
Miya

Reputation: 30

How to fetch json data from Mysql and convert it to an array in CodeIgniter

I have get the MySQL result as below format. I want to send this as JSON array format in an app.The keyword data are stored JSON array format in db. How to send this as JSON array ?

MySQL RESULT

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 ENCODE FORMAT

{
  "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\"}]"
    }
  ]
}

Upvotes: 1

Views: 1063

Answers (3)

jobinrjohnson
jobinrjohnson

Reputation: 558

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

I think this will solve it

Upvotes: 0

User123456
User123456

Reputation: 2738

First create a php array in the way you want to encode in-side the function or use the below sample in model (which extends CI_Model)

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

sample

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

Upvotes: 1

Miya
Miya

Reputation: 30

I use this method for my Question

    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();

Upvotes: 0

Related Questions