【问题标题】:Receive array of numbers in php (JSON)在 php (JSON) 中接收数字数组
【发布时间】:2015-02-01 14:17:25
【问题描述】:

我想在 php.ini 中从我的 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("to php: ", paramstodb.toString())" 上报)显示为:

到PHP :: [电话= [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);

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

【问题讨论】:

  • 看看这里试试这个:stackoverflow.com/a/3395811/1173391
  • 显示var_dump($phone);var_dump($phpArray); 的结果。在查询字符串中发送这么多数据并不理想,您可能会丢失一些数据。最好使用 POST 请求。
  • JSON 看起来像这样:{ "phone": [ "123", "456", "789"]} 但我无法获取值,因为它在 php 中没有数组(键缺失)。如何获取值?

标签: php android arrays json


【解决方案1】:

如果 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。

【讨论】:

    猜你喜欢
    • 2019-06-22
    • 2012-04-22
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多