在php(JSON)中接收数字数组

时间:2015-02-01 14:17:26

标签: php android arrays json

我想从php中获取我的JSON数组。 这样我在Android应用程序中从URL获取JSON字符串:

JSONObject json = jParser.makeHttpRequest(url_all_user, "GET", paramstodb);

要在php中接收[phone = 123]我使用:

if (isset($_GET["phone"])) {
    $phone = $_GET['phone'];

这适用于一个电话号码,但现在我需要一个以上的电话号码。

Logcat中的数据(报告为" Log.d("到php:",paramstodb.toString())")显示为:

to php :: [phone = [0127361744,0132782422,0137173813,0142534646,0123617637435,013391339494,01383375633,013878942423,013891748422,01389487285,014434354234,01848481371,018831789414,021238133441231,021371689411,02183718454,123,456]]

如何在php中获取数组中的所有数字? 到目前为止,这还不行:

if (isset($_GET["phone"])) {
    $phone = $_GET['phone'];
    $phpArray = json_decode($phone, true);

我希望你能再次帮助我; - )

1 个答案:

答案 0 :(得分:0)

如果PHP脚本的JSON输入确实是这个JSON

{ "phone": [ "123", "456", "789"] }

然后PHP的json_decode应该没有问题地处理它。 您可以尝试使用此代码来查看它实际工作并使用它来检测出现问题的位置:

// original JSON to send from the client
$jsonString = '{ "phone": [ "123", "456", "789"] }';

// build a query string with the JSON to send
$queryString = "?" . http_build_query(array("phone" => $jsonString));
echo "Query string to send is: " . $queryString  . PHP_EOL;

// PHP side: this is not a real HTTP GET request, but to pretend we have
// got some data in, we'll use the same query string, parse it, and store it
// in $params
$incoming = parse_url($queryString, PHP_URL_QUERY);
parse_str($incoming, $params);

// now print contents of "phone" parameter
echo "URL parameter phone contains " . $params["phone"] . PHP_EOL;

// JSON-decode the "phone" parameter
var_dump(json_decode($params["phone"], true));

这应该打印:

Query string to send is: ?phone=%7B+%22phone%22%3A+%5B+%22123%22%2C+%22456%22%2C+%22789%22%5D+%7D
URL parameter phone contains { "phone": [ "123", "456", "789"] }
array(1) {
  'phone' =>
  array(3) {
    [0] =>
    string(3) "123"
    [1] =>
    string(3) "456"
    [2] =>
    string(3) "789"
  }
}

显示JSON解码为正确的PHP数组。确切地说是字符串数组,而不是请求的数字。将字符串转换为PHP中的数字很容易,但也许你也可以确保在调用网站上发送数字而不是字符串。

如果您的原始代码不起作用,我猜输入的数据要么没有正确编码的JSON,要么正在进行一些魔法转义(魔法引用地狱,应该在今天的PHP中关闭,但可能是乱码的原因脚本输入)。

为了确保您的JSON数据不会被截断并且还能避免潜在的URL编码问题,我还建议通过HTTP POST而不是HTTP GET发送JSON。