在codeigniter中将多个数组合并到一个数组中?

时间:2017-08-07 11:25:32

标签: php codeigniter

您好我正在开发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"
  }
 ]

您可以注意到电子邮件:nomi_malik01@yahoo.com已收到来自电子邮件的几条消息: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.",
       "Hello!I am eating.",
       "Hello!Bye, I am going."
      } 
     ]
  } 

1 个答案:

答案 0 :(得分:0)

您可以使用array_push。我认为CodeIgniter中没有这方面的功能。

示例:https://www.w3schools.com/php/func_array_push.asp

你的例子:

$resp = array();
$first = true;

foreach($data as $d) {

    if($first === true) {
        $resp = array("from_user_email" => $d['from_user_email'],
                    "reg_name" => $d['reg_name'],
                    "pic_url" => $d['pic_url'],
                    "messages" => array());    
        $first = false;
    } else {
        array_push($resp['messages'], array("message" => $d['message']));
        //or
        array_push($resp['messages'], $d['message']);
    }
}