从数组中获取所有消息 - php

时间:2017-10-15 14:31:48

标签: php arrays json

我想获取所有消息并将其全部放入数组中,但我还有另一种方法可以按ID排序所有消息,例如: 我的json:

{"msg_c":[{"message":"Hi","sender":"2","receve":"3","name":"Muhamad Bagzada"},{"message":"Hello","sender":"3","receve":"2","name":"Danyal Join"},{"message":"What's up , How are you ?","sender":"2","receve":"3","name":"Muhamad Bagzada"},{"message":"fine and you ?","sender":"3","receve":"2","name":"Danyal Join"},{"message":"fine","sender":"2","receve":"3","name":"Muhamad Bagzada"}]}

我想要的是:

以不同的值显示数组中的混乱,(message_u:我的消息,messages_m:他的消息)

{
    "msg_c":
    [
        {"message_u":"Hi","sender":"2","receve":"3","name":"Muhamad Bagzada"},
        {"message_m":"Hello","sender":"3","receve":"2","name":"Danyal Join"},
        {"message_u":"What's up , How are you ?","sender":"2","receve":"3","name":"Muhamad Bagzada"},
        {"message_m":"fine and you ?","sender":"3","receve":"2","name":"Danyal Join"},
        {"message_m":"fine","sender":"2","receve":"3","name":"Muhamad Bagzada"}
    ]
}

php函数:

public function MessageApp ($user_id,$sender){
    $data ='';
    $Messg = mysqli_query($this->_join, "SELECT * FROM `messages` WHERE (`from` = '$sender' AND `to` = '$user_id') OR (`from` = '$user_id' AND `to` = '$sender')  ORDER BY dates ASC LIMIT 12 ");
    while ($m = mysqli_fetch_assoc($Messg)) {

    $from = $m['from'];
    $to = $m['to'];
    $chat = $m['chat'];
    $dates = $m['dates'];
    $id = $m['id'];
    if ($user_id === $sender) {
    $select_id = $to;
    }else{
    $select_id = $from;
    }
    $user = new user($from);
    $fullname = ($user->data()->fname)." ".($user->data()->lname);
    $gettype['msg_c'][] = array(
        'message' => $chat,
        'sender' => $from,
        'receve' => $to,
        'name'=>$fullname
     );

    $data = json_encode($gettype);

    }

    return json_encode($gettype);
}

我在这里调用了json数据:

<?php

include $_SERVER['DOCUMENT_ROOT']."/php/core/init.php";
include $_SERVER['DOCUMENT_ROOT']."/php/core/connect.php";
$my_id = input::get('user_id');
$user = new user($my_id);
$sender = $user->data()->id;
$db = db::getInstance();

$message = new message();

$id = input::get("id"); 
$user = new user($id);
$user_id = $user->data()->id;

echo $message->MessageApp($user_id,$sender);

?>

1 个答案:

答案 0 :(得分:0)

在msg_c中构建行时,可以在不同情况下分离set键,如下所示

Y.shape= (38932,)

甚至可以在if else语句中构建数组,然后重用代码