0

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...

Community
  • 1
  • 1
Mendes
  • 17,489
  • 35
  • 150
  • 263
  • 1
    `$ret = (object)[];` means `$ret` is an instance of `stdClass` (though god know why you're even doing that), then later you use `$ret[] = ` which you can't do because `$ret` is an object, not an array. – Jonnix Jun 02 '16 at 17:57
  • 1. Do you use PHP7? 2. Did you mean an object without a class? – guessimtoolate Jun 02 '16 at 17:59
  • By the way, function is called json_encode – splash58 Jun 02 '16 at 17:59
  • can you post what you expect your json to look like? – jbe Jun 02 '16 at 17:59
  • Post edited: `splash`: I´m copying from a VM without copy+paste feature - code fixed; `guessimtoolate`:Using PHP 5.6.22; `Jon`: good point - this shall be the problem, but: how to add a new property to `stdClass` ? – Mendes Jun 02 '16 at 18:03
  • 1
    If you only need it to encode it to JSON why not just use an associative array? It'll be encoded to a JSON object. – guessimtoolate Jun 02 '16 at 18:05

2 Answers2

1

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}
splash58
  • 26,043
  • 3
  • 22
  • 34
0

How about:

public static function getData()
{
    $data = [
        "Name" => "John",
        "Address" => "A Ave 222",
        "Age" => 32,
    ];
    return json_encode($data);
}

?

guessimtoolate
  • 8,372
  • 2
  • 18
  • 26