-1

I have an array that looks like this.

$data['id'][0] = 123;
$data['id'][1] = 302;

.... And so on, I have to convert this to an object like this,

$object = ['id' => [123, 302.....]];

I can't seem to achieve this in a way like this

$object = (object)$data;

How can I do this in PHP? What's the most efficient way of doing it. Thanks

rksh
  • 3,920
  • 10
  • 49
  • 68
  • 1
    there are many ways to do that, `json_decode(json_encode(..))`, using new arr with stdClass – Murad Hasan May 29 '16 at 07:01
  • [helpful link](https://www.phpro.org/examples/Convert-Object-To-Array-With-PHP.html) – Murad Hasan May 29 '16 at 07:04
  • 1
    Possible duplicate of [How to convert an array to object in PHP?](http://stackoverflow.com/questions/1869091/how-to-convert-an-array-to-object-in-php) – Jamie Poole May 29 '16 at 07:12
  • What you mean by `$object = ['id' => [123, 302.....]];`??? See the example: [https://3v4l.org/eFFl3](https://3v4l.org/eFFl3) – Murad Hasan May 29 '16 at 07:51

1 Answers1

0

create the object class like so:

class myObject {
  public $myArray;

  public function __construct($myArray = array()) {
     foreach ($myArray as $value)
     {
        $this->myArray[] = $value;
     }
  }

}

And when you initiate a new object, you'll be able to pass the values like so:

$newArray = new myObject($data['id']);

Then if you wanted to see what is inside your array, just do:

foreach ($newArray->myArray as $value)
{
  echo "{$value}<br>";
}
Webeng
  • 7,050
  • 4
  • 31
  • 59