Mendes Mendes - 6 months ago 9
JSON Question

Object without class: adding new fields and returning as JSON

My question is a variation of the following post here added to JSON logic. I´m using PHP 5.6.22

I need to build a class without an object at runtim to build a JSON object of same type to be returned to the client.
My code:

public static function getData()
{
$columns = array ("Name", "Address", "Age" );
$values = array ("John", "A Ave 222", 32 );

$ret = (object)[];
$index = 0;

foreach ($columns as $col)
{
$value = $values[$index++];
$ret[] = (object) [$col => $value]; // Error here
}

return json_encode($ret);
}


When running that I get the following error:

<b>Fatal error</b>: Cannot use object of type stdClass as array in <source filename> on line <linenumber>


Help appreaciated to solve that...

Answer

In PHP you can add new property to array just by setting it

$columns = array ("Name", "Address", "Age" );
$values  = array ("John", "A Ave 222", 32 );

$ret = (object) [];
$index = 0;

foreach ($columns as $col)
{
    $value = $values[$index++];
    // You can create and add new property to object in php by such way
    $ret->$col = $value; 
}

echo json_encode($ret);  // {"Name":"John","Address":"A Ave 222","Age":32}