如何在PHP中循环访问接收的数组并查询数据库以返回新数组? [英] How do I loop through a received array in PHP and query the database to return a new array?
问题描述
我在php中有这个代码:
I have this code in php:
<?php
include_once("JSON.php");
$json = new Services_JSON();
//1. PROCESS RECEIVED ARRAY
$handle = fopen("php://input", "rb");
$http_raw_post_data = '';
while (!feof($handle)) {
$http_raw_post_data .= fread($handle, 8192);
}
fclose($handle);
//just decode to see what kind of object it is
$post_data = json_decode($http_raw_post_data,true);
if (is_array($post_data))
$response = array("status" => "ok", "code" => 0, "original request" => $post_data);
else
$response = array("status" => "error", "code" => -1, "original_request" => $post_data);
//CALL DB QUERY
$link = mysql_pconnect("localhost", "user", "pass") or die("Could not connect");
mysql_select_db("mydb") or die("Could not select database");
//CREATE FINAL ARRAY TO RETURN
$arrayToReturn = array();
//----------------------THIS FAILS, POSSIBLY DUE TO WHEN IT RETURNS
foreach ($post_data as $value)
{
//CREATE QUERY
$result = mysql_query("SELECT username, SUM(points) AS PUNTOS FROM tags WHERE username='$value' GROUP BY username");
echo "executing query...";
//EXECUTE QUERY & ADD EACH USER/POINTS DICTIONARY TO $resultado ARRAY
$resultado = array();
while($obj = mysql_fetch_object($result))
{
$resultado[] = $obj;
}
//STORE RESULTS IN NEW OBJECT TO RETURN
$arrayToReturn[] = $resultado;
}
?>
我刚刚编辑了我的原始问题,现在我得到我的数组...响应字符串记录我的iOS应用程序是从服务器响应,是:
I just edited the my original question and now I get my array...the response string logged by my iOS app, which is from the server response, is:
正在执行查询...数组
正在执行查询...数组
[[ {username:xcodeSim,PUNTOS:5}],[{username:dannyrodri,PUNTOS:5}]]
executing query...Array executing query...Array [[{"username":"xcodeSim","PUNTOS":"5"}],[{"username":"dannyrodri","PUNTOS":"5"}]]
不知道字数组是从哪里来的,但我得到一个有两个数组的数组。我想我只需要调整它,使其成为一个只有2个字典的数组。
Not sure where the word Array is coming from but I am getting an array with two arrays in it. I guess I just have to tweak it to make it into an array with just 2 dictionaries in it. How do I encode this back to my iOS app?
推荐答案
请尝试以下操作:
$array_to_return = array();
if ($post_data) {
$usernames = implode(',', array_map(function($u) {
return "'" + mysql_real_escape_string($u) + "'";
}));
$result = mysql_query("SELECT username, SUM(points) AS PUNTOS FROM tags WHERE username IN ($usernames) GROUP BY username") or die (mysql_error());
while ($obj = mysql_fetch_object($result)) {
array_to_return[] = $obj;
}
}
echo json_encode($array_to_return);
这篇关于如何在PHP中循环访问接收的数组并查询数据库以返回新数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!