如何从codeigniter中的一个数组中的多个数组中获取并显示特定用户的多个数据?

时间:2017-08-02 05:04:44

标签: codeigniter mysqli

您好我正在开发codeigniter中的聊天API。这是我的控制器和型号

//show message controller
public function to_user()
{
    $data = json_decode(file_get_contents('php://input'));
    $userto = $data->{'userto'};
    $data=$this->um->to_user($userto);
    echo json_encode($data);
}

//show message model
 function to_user($userto)
 { 
      $this->db->select('message,from_user_email,reg_name,pic_url');
        $this->db->from('t_chat_msg');
        $this->db->where('to_user_email', $userto);
        $this->db->join('registration','t_chat_msg.from_user_email=registration.email','inner');
        $query = $this->db->get()->result_array();

        return $query; 
 } 

当我使用参数点击邮递员获得结果时。

 {
"userto":"nomi_malik01@yahoo.com"
 }

 Result:

 [
 {
 "message": "Hi.",
 "from_user_email": "tapy@live.com",
 "reg_name": "Tapy",
 "pic_url": "https://www.develooped.com/qrcode/images/avatar.png"
  },
 {
  "message": "Hello!Testing.",
  "from_user_email": "tapy@live.com",
  "reg_name": "Tapy",
  "pic_url": "https://www.develooped.com/qrcode/images/avatar.png"
 },
 {
  "message": "hi,again",
  "from_user_email": "tapy@live.com",
  "reg_name": "Tapy",
  "pic_url": "https://www.develooped.com/qrcode/images/avatar.png"
  }
]

您可以注意到电子邮件:nomi_malik01@yahoo.com收到了很多来自电子邮件的消息:tapy@live.com但是它们显示在不同的数组中,但我希望以单个数组显示它们。请帮帮我。

1 个答案:

答案 0 :(得分:0)

您的控制器更改

public function to_user()
{
  $data = json_decode(file_get_contents('php://input'));
  $userto = $data->{'userto'};
  $data=$this->um->to_user($userto);
  foreach ($data as $key => $val) {
        $new_arr[$val['from_user_email']]['from_user_email']=$val['from_user_email'];
        $new_arr[$val['from_user_email']]['reg_name']=$val['reg_name'];
        $new_arr[$val['from_user_email']]['pic_url']=$val['pic_url'];
        $new_arr[$val['from_user_email']]['message'][]=$val['message'];
    }
  //set page header
  $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode($new_arr));
}

结果输出

//when sender email is same
{
    "tapy@live.com": {
        "from_user_email": "tapy@live.com",
        "reg_name": "Tapy",
        "pic_url": "https://www.develooped.com/qrcode/images/avatar.png",
        "message": [
            "Hi.",
            "Hello!Testing.",
            "hi,again"
        ]
    }
}

//when sender email is diff.

{
    "tapy@live1.com": {
        "from_user_email": "tapy@live1.com",
        "reg_name": "Tapy",
        "pic_url": "https://www.develooped.com/qrcode/images/avatar.png",
        "message": [
            "Hi."
        ]
    },
    "tapy@live.com": {
        "from_user_email": "tapy@live.com",
        "reg_name": "Tapy",
        "pic_url": "https://www.develooped.com/qrcode/images/avatar.png",
        "message": [
            "Hello!Testing.",
            "hi,again"
        ]
    }
}