【发布时间】: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 输入不匹配。