美好的一天![/ p>
我有这个代码块,我创建了一个JSON字符串,我有一个动态数据,所以我需要的也是一个密钥的动态名称..
if (mysql_num_rows($result) > 0) {
$response["members"] = array();
$x = 0;
$members = array();
while ($row = mysql_fetch_array($result)) {
$members = array();
$members["member" + (string)$x] = array();
$member["member_id"] = $row["member_id"];
$member["firstname"] = $row["firstname"];
$member["mi"] = $row["mi"];
$member["lastname"] = $row["lastname"];
$member["email"] = $row["email"];
$member["username"] = $row["username"];
$member["password"] = $row["password"];
$member["guild_id"] = $row["guild_id"];
$member["guild_name"] = $row["guild_name"];
$member["guild_code"] = $row["guild_code"];
array_push($members["member" + (string)$x], $member);
$x++;
}
array_push($response["members"], $members);
echo json_encode($response);;
}
在JQuery中这种方法有效..我的问题是,有什么方法可以用php实现它吗?如果你知道我会很高兴知道...
答案 0 :(得分:1)
如果您想要实现members
数组包含密钥为member0
,member1
等的单个记录,那么您可以继续:
if (mysql_num_rows($result) > 0) {
$x = 0;
$members = array();
while ($row = mysql_fetch_array($result)) {
$member = array();
$member["member_id"] = $row["member_id"];
$member["firstname"] = $row["firstname"];
$member["mi"] = $row["mi"];
$member["lastname"] = $row["lastname"];
$member["email"] = $row["email"];
$member["username"] = $row["username"];
$member["password"] = $row["password"];
$member["guild_id"] = $row["guild_id"];
$member["guild_name"] = $row["guild_name"];
$member["guild_code"] = $row["guild_code"];
$members["member$x"] = $member;
$x++;
}
$response["members"] = $members;
echo json_encode($response);
}
答案 1 :(得分:1)
1.Suggestion:-stop使用已弃用+删除(php5 + php7)版本的mysql_*
。移向mysqli_*
OR PDO
以及prepared statements
(防止Sql注入) )
2.为什么要创建不必要的数组和多次推送。不需要这样做。如下所示: -
$response["members"] = array();//put outside
if (mysql_num_rows($result) > 0) {
$x = 0;
while ($row = mysql_fetch_array($result)) {
$response["members"][$x]["member_id"] = $row["member_id"]; //assign value directly to the resultant array
$response["members"][$x]["firstname"] = $row["firstname"];
$response["members"][$x]["mi"] = $row["mi"];
$response["members"][$x]["lastname"] = $row["lastname"];
$response["members"][$x]["email"] = $row["email"];
$response["members"][$x]["username"] = $row["username"];
$response["members"][$x]["password"] = $row["password"];
$response["members"][$x]["guild_id"] = $row["guild_id"];
$response["members"][$x]["guild_name"] = $row["guild_name"];
$response["members"][$x]["guild_code"] = $row["guild_code"];
$x++;
}
}
if(count($response["members"])>0){ //check finally that array is not empty
echo json_encode($response); //echo json encoded array data
}