How to retrieve JSON array value to PHP?

I am creating an array in javascript and trying to loop through the values for inclusion in db. I would be grateful if someone could point out the correct way to deal with arrays in php because all I am getting is empty values…

If I do var_dump($output); it shows an array which I have posted below. How do I get the values from array as I am new to this level of coding. Many thanks

$info = $_POST['info'];
$output = json_decode($info);
var_dump($output);
foreach($output as $res)
{
    echo $res;
}

var_dump output

array(1) { [0]=> object(stdClass)#2 (4) { ["Service"]=> string(8) "Standard" ["Activity"]=> string(14) "New Box Intake" ["Dept"]=> string(4) "DEMO" ["Box"]=> string(11) "DEMOBOX0014" } }

json_decode takes an optional second parameter that indicates whether you want objects or arrays returned. By default you get objects, so for example to get to that “Service” value you’d need

$output[0]->Service

Most of the time though it’s easier to instruct json_decode to return arrays, like so:

$info = $_POST['info'];
$output = json_decode($info, true); // <-- true = return arrays instead of objects
var_dump($output);
foreach($output as $res)
{
    echo $res;
}

Is this the best way to handle an array in php? Many thanks

Most PHP code I see does use json_decode set to return an array instead of objects, yes.

Thank you for your help

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.