【问题标题】:Creating an empty array with key value用键值创建一个空数组
【发布时间】:2017-03-30 01:40:00
【问题描述】:

我正在尝试在 php 中创建一个数组,该数组将通过 ajax 调用在 javascript 中被解析为 json。我注意到用$empty = array() 实例化的数组的第一个索引返回为{"0":[{..values here..}], "success":true}。理想情况下,我会使用reply.datareply.success 访问它。回复。成功有效,但我似乎无法找到如何创建没有 0 作为第一个索引的数组。

我的php端代码:

    $result = array();
    $record = array();
    $resp = mysqli_query($this->conn, $sql);
    if(mysqli_num_rows($resp)>0){
        while($row = mysqli_fetch_assoc($resp)){
            $record = array();
            foreach($row as $key => $val){
                $record[$key] = $val;
            }
            array_push($result,$record);
            unset($record);
        }
        //return json_encode($result, JSON_PRETTY_PRINT);
        return $result;

当我在 javascript 中访问它时

 success: function(data){
        data = JSON.parse(data);
        if(data.success==true){  //able to access success with "data.success"
            //there is an empty
            $scope.conn = "connecting to room";
            console.log(data.data.room_id);  //does not work because index is 0
            console.log(JSON.stringify(data));

返回什么

{"0":[{"room_id":"20","host_id":"","resp_id":"","offer":"","answer":"","status":"0"}],"success":true}

【问题讨论】:

    标签: php arrays json key associative-array


    【解决方案1】:

    用这个,

    $result = array();
    $resp = mysqli_query($this->conn, $sql);
    if(mysqli_num_rows($resp)>0){
        while($row = mysqli_fetch_assoc($resp)){
            foreach($row as $key => $val){
                $result["data"][$key] = $val
            }
        }
    }
    //return json_encode($result, JSON_PRETTY_PRINT);
    return $result;
    

    【讨论】:

    • 这回答了我的问题,但我应该补充一点,我通过回复函数运行我的回复,所以现在它返回这个 {"reply":[{"data":{"room_id":"20",...}}],"success":true} 为什么它似乎返回一个数组? php回复函数:public function reply($success,$data){ $reply = array(); if(sizeof($data)!=0){ foreach($data as $key => $val){ $reply['reply'][$key] = $val; } } return json_encode($reply); }
    • 具有数字键、以0 开头并且数字中没有任何间隔(即1、3、5)的php 数组将被转换为json_encode 中的数组。这是非常标准的,因为它们都可以在 JS 中使用。您还可以将JSON_FORCE_OBJECT 常量传递给 json_encode。
    【解决方案2】:

    我认为您将过程复杂化了

    foreach 循环似乎是不必要的,因为您可以将 $row 加载到数组中。

    public function xxx()
    {
        $result = array();
        $resp = mysqli_query($this->conn, $sql);
        if(mysqli_num_rows($resp)>0) {
            $result['success'] = 'true';
    
            while($row = mysqli_fetch_assoc($resp)){
                $result['data'][] = $row;
            }
    
        } else {
            $result['success'] = 'false';
        }
        return $result;
    }
    
    // instantiate object 
    //$obj = new Whatever the class is called()
    echo json_encode($obj->xxx());
    

    【讨论】:

      猜你喜欢
      • 2020-08-02
      • 2019-01-01
      • 2019-01-26
      • 2022-01-12
      • 2015-06-29
      • 1970-01-01
      • 2012-07-14
      • 2013-05-17
      • 1970-01-01
      相关资源
      最近更新 更多