json编码二维数组

时间:2018-05-09 20:52:04

标签: php json ajax

我有这个PHP代码:

$sql = read_sql( 'SELECT * FROM ges_messagerie_mess WHERE id_channel = ' . $_POST["idconv"] . ' AND id_private = ' . $_POST["idprive"] . ' AND iduser != ' . $_SESSION['compte'] . ' AND statut = 1 ORDER BY datecreation ASC' );

if ( $sql ) {
    foreach ( $sql as $message ) {
        $datemessage         = utf8_encode( strftime( "%d %b %Y", strtotime( $message["datecreation"] ) ) );
        $data['datemessage'] = $datemessage;

        $heureTicket          = utf8_encode( strftime( "%H:%M", strtotime( $message["datecreation"] ) ) );
        $data['heuremessage'] = $heureTicket;

        $data['success'] = nl2br( $message["message_user"] );

        $data['logo'] = getLogo( $message["idbase"] );

    }
}

 echo json_encode( $my2dimensionalArrayHere );

但是我正在寻找如何创建一个包含2个维度的数组来发送给我的AJAX调用!然后在Ajax部分,我如何使用我的二维数组获取数据?

非常感谢您的帮助:)

1 个答案:

答案 0 :(得分:1)

您可以使用[] operator$data数组推送到$my2dimensionalArray

$my2dimensionalArray[] = $data;

代码可以是:

$my2dimensionalArray = [];
if ( $sql ) {
    foreach ( $sql as $message ) {
        $datemessage         = utf8_encode( strftime( "%d %b %Y", strtotime( $message["datecreation"] ) ) );
        $data['datemessage'] = $datemessage;

        $heureTicket          = utf8_encode( strftime( "%H:%M", strtotime( $message["datecreation"] ) ) );
        $data['heuremessage'] = $heureTicket;

        $data['success'] = nl2br( $message["message_user"] );

        $data['logo'] = getLogo( $message["idbase"] );

        $my2dimensionalArray[] = $data;
    }
}
echo json_encode( $my2dimensionalArray );

输出如下:

[
 {"datemessage":"01 Jan 2018","heuremessage":"00:00","success":"success","logo":"logo"},
 {"datemessage":"01 Jan 2018","heuremessage":"00:00","success":"success","logo":"logo"},
 {"datemessage":"01 Jan 2018","heuremessage":"00:00","success":"success","logo":"logo"}
]