AhmedFaud
AhmedFaud

Reputation: 231

How create object PHP?

There is a object from function result():

foreach ($query->result() as $row)
{
   echo $row->title;
   echo $row->name;
   echo $row->body;
}

How I can get the same object from the next array:

$arr[$key] = array(
     'Reason' => $status,
     'Time'   => $val->time,
      'IdUser' => $val->dot,
       'Date'   => $val->date,
        'IdUser' => $val->IdUser,
          'Photo'  => $val->Photo
);

I tried (object)$arr

Upvotes: 1

Views: 376

Answers (2)

Damien Pirsy
Damien Pirsy

Reputation: 25445

With $key being a string, it's pretty easy, just cast to object both:

$key = 'test';
$arr[$key] = (object)array(
     'Reason' => 1,
     'Time'   => 100,
      'IdUser' => $val->dot,
       'Date'   => $val->date,
        'IdUser' => $val->IdUser,
          'Photo'  => $val->Photo
);
$row = (object)$arr;

var_dump($row->test);
/*
object(stdClass)#1 (5) {
  ["Reason"]=>
  int(1)
  ["Time"]=>
  int(100)
  ["IdUser"]=>
  NULL
  ["Date"]=>
  NULL
  ["Photo"]=>
  NULL
}
*/
echo $row->test->Time; //100

If $key is a number...you're out of luck. In some php versions, $row->{'2'}, for instance, would work, but mainly it won't - and if you want to use a numerical index as object property you're making some design mistake somewhere. See this codepad for the source of my example: http://codepad.org/Y7F2xCnj

Upvotes: 0

Apuig
Apuig

Reputation: 350

You have a good example on http://php.net/manual/es/language.oop5.php

$obj = (object) array('foo' => 'bar', 'property' => 'value');

echo $obj->foo; // prints 'bar'
echo $obj->property; // prints 'value'

Your associative array is converted in an object and you can get his properties now.

There are anothers ways to convert an array to object, take the best solution for you:

How to convert an array to object in PHP?

Upvotes: 1

Related Questions