jquery - PHP array string key add number at the end -
good day fellas!
i have block of code create json string , have dynamic number of data need dynamic name key..
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);; }
in jquery type of method works.. question is, there way can achieve using php? if know happy know...
1.suggestion:-stop using deprecated+removed(php5 +php7) version of mysql_*
.move towards mysqli_*
or pdo
along prepared statements
(prevent sql injection)
2.why creating unnecessary array , multiple push.no need that.do below:-
$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 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 array not empty echo json_encode($response); //echo json encoded array data }
Comments
Post a Comment