【问题标题】:Is there a way to access a json object elements using PHP有没有办法使用 PHP 访问 json 对象元素
【发布时间】:2021-02-04 13:24:17
【问题描述】:

我正在尝试使用 PHP 从我自己的 API 获取数据 \
我的 PHP 代码:

$cart = json_decode(file_get_contents("php://input",true));
foreach ($cart->thoubss as $a){
    echo($a['0']); // trying to get the first element in the array (4) in the first iteration and then (3) in the second iteration
    echo($a['1']); // trying to get the first element in the array (5) in the first iteration and then (3) in the second iteration
}

我的 JSON 输入: {"thoubss":"{'0': [4, 5], '1': [5, 3]}"}

我得到 PHP Warning: Invalid argument supplied for foreach()

print_r($cart) 输出

stdClass Object
(
    [thoubss
] => {'0': [
        4,
        5
    ], '1': [
        5,
        3
    ]
}
)

【问题讨论】:

  • {"thoubss":"{'0': [4, 5], '1': [5, 3]}"} 输入具有 thoubss 键,其中包含字符串 {'0': [4, 5], '1': [5, 3]}。您不能为 foreach() 提供字符串。
  • print_r($cart) 您发布的输出与您的 JSON 输入不匹配。

标签: php json api post


【解决方案1】:

试试

    $cart = json_decode(file_get_contents("php://input",true),true);

json_decode 将返回一个数组而不是一个 stdClass 对象

【讨论】:

  • 我仍然收到(PHP 警告:为 foreach() 提供的参数无效)
  • 在您的特定情况下,在将第二个参数添加到 json_decode 后,尝试将 $cart->thoubss 替换为 $cart['thoubss']
  • 我修改为 $cart = json_decode(file_get_contents("php://input",true),true);和 foreach ($cart['thoubss'] as $a){ echo($a['0']); } 但仍然出现同样的错误
  • @NicolasF 我猜你没有用 OP 的 JSON 输入字符串测试你的代码。
【解决方案2】:

你也可以使用这个方法。

$cart = json_decode(file_get_contents("php://input",true),true);

这将返回一个如下所示的数组。

$cart = array(
    "thoubss" => array(
        '0' => array(4, 5),
        '1' => array(5, 3)
    )
);

现在你可以像下面这样使用:

foreach ($cart['thoubss'] as $a){
    echo $a[0];
    echo $a[1];
}

【讨论】:

  • 我复制并粘贴了您的代码,但仍然收到 PHP 警告:foreach() 提供的参数无效
  • 打印你的$cart变量来检查它是否返回一个数组。
  • @SureshChand 我猜你没有用 OP 的 JSON 输入字符串测试你的代码。
  • @SureshChand 数组 ([thoubss] => {'0': [1, 1], '1': [1, 1] })
猜你喜欢
  • 2011-01-23
  • 2018-11-08
  • 2016-03-31
  • 2014-02-25
  • 1970-01-01
  • 2022-08-12
  • 2014-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多