[英]Creating an empty array with key value
I am trying to create an array in php that will be parsed as json in javascript via ajax call. 我正在尝试在php中创建一个数组,该数组将通过ajax调用在javascript中解析为json。 I noticed that the first index of an array instantiated with
$empty = array()
returns as {"0":[{..values here..}], "success":true}
. 我注意到用
$empty = array()
实例化的数组的第一个索引返回为{"0":[{..values here..}], "success":true}
。 Ideally I would access it using reply.data
and reply.success
. 理想情况下,我将使用
reply.data
和reply.success
访问它。 The reply. 答复。 success works, but I can't seem to find how to create an array without a 0 as the first index.
成功有效,但我似乎找不到如何创建一个没有0作为第一个索引的数组。
My php side code: 我的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;
When I access it within javascript 当我在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));
What it returns 它返回什么
{"0":[{"room_id":"20","host_id":"","resp_id":"","offer":"","answer":"","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;
I think you are rather over complicating the process 我认为您宁可将流程复杂化
The foreach loop appears to be unnecessary as you can just load $row into the array. 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.