Saturday, February 19, 2022

[FIXED] how change table names in json array codeigniter

Issue

Sorry I'm not sure if my question is correct. My problem is I'm trying to change the table names in json format that are produced by calling a function in codeigniter. Is this possible?

I have 2 items on my database to begin with....

This Json is produced by the controller & model below:

{

"data": [
   {
    "real_id": "1"
   },
   {
     "real_id": "2"
    }
  ]
}

Currently I have this on my controller:

//-----CONTROLLER:

$messages = $this->message_model->get_messages();

if(count($messages) > 0){
  

  $this->response(array(
    "data" => $messages
  ) );
  
}

And my model:

// Model 
public function get_messages(){

    $this->db->select("*");
    $this->db->from("myDataBase");
    $query = $this->db->get();

    return $query->result();
     
    }

If possible, I wanted to change the "real_id" and make it like "FAKE_id" like the example below:

{
   
    "data": [
       {
        "FAKE_id": "1"
       },
       {
         "FAKE_id": "2"
        }
      ]
    }

I tried something like this but it only shows 1 (one) item.

...
if(count($messages) > 0){
      foreach ($messages as $data) {
         $id =  $data->real_id;
         $arr = array(
          "FAKE_id" => $id
           ); 
        }
      $result = $arr;
 
      $this->response(array(
       
        "data" => $messages
      ) );
      
    }

The output of that is this which is wrong because only one is displaying:

{
  
    "data": [
       {
        "FAKE_id": "2"
       },
       
      ]
    }

Thanks in advance!


Solution

In your query just change the column names instead of selecting the default ones like so:

$this->db->select("real_id AS fake_id");
$this->db->from("myDataBase");
$query = $this->db->get();


Answered By - marcogmonteiro

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.