如何将数据从 JSON 数组提取到变量并将变量传递给 PHP 函数


How to extract data from a JSON array to variables and pass variables to a PHP function

我有一个Java程序,它向PHP文件发送HTTP POST请求。我需要 PHP 脚本将 JSON 数据提取到一些变量,并使用这些变量(参数)调用 PHP 函数。请在下面找到 PHP 代码。

<?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        $data = json_decode(file_get_contents("php://input"), true);
        var_export($data);      
    }
    else
    {
        var_export($_SERVER['REQUEST_METHOD']);
    }
?> 

在 Java 中创建的 JSON 对象

JSONObject json = new JSONObject();
json.put("name", "Dash");
json.put("num", new Integer(100));
json.put("balance", new Double(1000.21));

请帮助我了解如何将 JSON 数组数据提取到变量以及如何进行调用。

一旦你运行了json_decode(),$data只是一个"普通"的php数组,里面有"普通"的php值。
因此,例如

/*
JSONObject json = new JSONObject();
json.put("name", "Dash");
json.put("num", new Integer(100));
json.put("balance", new Double(1000.21));
=>
*/
// $input = file_get_contents("php://input");
$input = '{"name":"Dash","num":100,"balance":1000.21}';
$data = json_decode($input, true);
$response = array(
    'name_rev'      => strrev($data['name']),
    'num_mod_17'    => $data['num'] % 17,
    'balance_mul_2' => $data['balance'] * 2
);
echo json_encode($response, JSON_PRETTY_PRINT); // you might want to get rid off JSON_PRETTY_PRINT in production code

指纹

{
    "name_rev": "hsaD",
    "num_mod_17": 15,
    "balance_mul_2": 2000.42
}

另外两个提示:

  • 您应该测试$data是否包含您期望的所有元素,在访问它们之前,请参阅 http://docs.php.net/isset , http://docs.php.net/filter 等
  • 一个名为 balance 的 Java Double()。Java Double 是 64 位 IEEE 754 浮点数。您可能会在某一点(如果不是范围超过)达到精度限制,请参阅在 java 应用程序中用于赚钱的最佳数据类型是什么?