创建一个包含键值的空数组


Creating an empty array with key value

我试图在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":"","answerswer":"","status":"0"}],"success":true}

use this,

$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;

我认为你把这个过程弄得太复杂了。

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());