有没有一种方法可以使用PHP访问json对象元素

时间:2020-10-21 15:23:01

标签: php json api post

我正在尝试使用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
    ]
}
)

2 个答案:

答案 0 :(得分:0)

尝试

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

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

答案 1 :(得分:0)

您也可以使用此方法。

$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];
}