[英]Creating an empty array with key value
我正在嘗試在php中創建一個數組,該數組將通過ajax調用在javascript中解析為json。 我注意到用$empty = array()
實例化的數組的第一個索引返回為{"0":[{..values here..}], "success":true}
。 理想情況下,我將使用reply.data
和reply.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.