0

I am trying to insert data from a database into a stdClass but for some reason, I get a notice Notice: Array to string conversion in data.php on line 47.

I'm creating 2 stdClasses, one for each vehicle and one general that contains all of them. When I'm trying to insert the vehicle's stdClass into the general one I get the notice.

Here is my code (Notice I wrote where line 47 is):

$data = new stdClass();

while($row = mysqli_fetch_array($tresult)) {
    $vehicle = new stdClass();
    $vehicle->name = $row['name'];
    $vehicle->position = $row['position'];

    $data->$row['name'] = $vehicle; //Line 47
}

What am I missing here? Thank you

morha13
  • 1,847
  • 3
  • 21
  • 42
  • 4
    Try `$data->{$row['name']}` perhaps? see: http://php.net/manual/en/language.variables.variable.php – ficuscr Sep 13 '17 at 20:10
  • try a var_dump($vehicle); to see if is an array or string, regard :). –  Sep 13 '17 at 20:11
  • @ficuscr You're a genius... Thank you :D Write it as an answer and I'll accept it as soon as it lets me – morha13 Sep 13 '17 at 20:12
  • All good. Glad you got it sorted. Hook OsDev up. `"Same is good for array element output in a double quote string. {$foo[1]}"` – ficuscr Sep 13 '17 at 20:13

1 Answers1

4

Try to assign this way, because you have to interpolate the variable

$data->{$row['name']} = $vehicle

OsDev
  • 1,243
  • 9
  • 20
  • Thank you and ficuscr, it fixed it! I'll accept the answer just when it lets me.. – morha13 Sep 13 '17 at 20:13
  • 2
    Just a note for those who want to learn more about how this works, this is called [Complex Syntax](https://stackoverflow.com/a/2596838/5827005) – GrumpyCrouton Sep 13 '17 at 20:19