0

我在 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 应用程序记录的响应字符串来自服务器响应,是:

执行查询...数组执行查询...数组 [[{"username":"xcodeSim","PUNTOS":"5"}],[{"username":"dannyrodri","PUNTOS":"5" }]]

不确定 Array 这个词是从哪里来的,但我得到了一个包含两个数组的数组。我想我只需要调整它以使其成为一个只有 2 个字典的数组。如何将其编码回我的 iOS 应用程序?

4

2 回答 2

0

$result 由于引号,查询将失败试试这个:

$result = mysql_query("SELECT username, SUM(points) AS PUNTOS FROM tags WHERE username='".$_POST["userNa"]."' GROUP BY username");
于 2013-07-04T17:14:51.660 回答
0

尝试这个:

$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);
于 2013-07-04T17:22:41.853 回答