1

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

2
  • Duplicate question. Answer here: http://stackoverflow.com/questions/1869091/convert-array-to-object-php Commented Nov 7, 2014 at 21:07
  • possible duplicate of Convert Array to Object PHP Commented Nov 7, 2014 at 21:26

2 Answers 2

1

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?

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.