繁体   English   中英

用键值创建一个空数组

[英]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":"","answer":"","status":"0"}],"success":true}

用这个,

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM