0

I am trying to get a data from my own API using PHP \
My PHP code :

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

My JSON input : {"thoubss":"{'0': [4, 5], '1': [5, 3]}"}

I am getting PHP Warning: Invalid argument supplied for foreach()

print_r($cart) output

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

2 Answers2

0

Try with

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

json_decode will return an array instead of an stdClass object

Nicolas F
  • 72
  • 6
  • I am still getting (PHP Warning: Invalid argument supplied for foreach()) – fahi Oct 21 '20 at 15:37
  • In your specific case and after adding the second argument to json_decode try replacing $cart->thoubss by $cart['thoubss'] – Nicolas F Oct 21 '20 at 15:39
  • I modified it to $cart = json_decode(file_get_contents("php://input",true),true); and foreach ($cart['thoubss'] as $a){ echo($a['0']); } but still getting the same error – fahi Oct 21 '20 at 15:42
  • @NicolasF I guess you didn't tested your code with OP's JSON input string. – omegastripes Oct 21 '20 at 16:22
0

You can use this method also.

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

This will return an array like below.

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

Now you can use like below:

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