我正在尝试在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}
答案 0 :(得分: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;
答案 1 :(得分:1)
我认为你过度复杂化了这个过程
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());