Skip to content
Advertisement

array of arrays to array of objects php

I am trying to convert the associative array to an array of objects.

$assoc = array (
array(
    'prop1'=>'val1',
    'prop2'=>'val2',
),

array(
    'prop1'=>'val1',
    'prop2'=>'val2',
),
)

Here Is the code I have so far:

class Assoc {
public function setObject($assoc) {
    $this->assoc[] = new Obj($assoc);
}
}
class Obj {
public function __construct($item) {
    foreach ( $item as $property=>$value ) {
        $this->{$property} = $value;
    }
}
}

$test = New Assoc();
$test->setObject($assoc);

This code will work for a single array but not an array of arrays. If you could help with what I believe to be the loop in the setObject function.

Advertisement

Answer

EDIT for specific object:

To adhere to your existing style as close as possible without messing with array_map voodoo:

class Assoc {
  public function setObject($assoc) {
    foreach ($assoc as $arr) {
      $this->assoc[] = new Obj($arr);
    }   
  }
}
class Obj {
   public function __construct($item) {
     foreach ( $item as $property=>$value ) { 
       $this->{$property} = $value;
     }  
   }   
}

$test = New Assoc();
$test->setObject($assoc);

Original:

If you just need generic conversion, and not into specific custom objects (not exactly clear in your post?) you can try this:

$new_array = array();
foreach ($assoc as $to_obj)
{
  $new_array[] = (object)$to_obj;
}

// Print results
var_dump($new_array);

outputs:

array(2) {
  [0]=>
  object(stdClass)#1 (2) {
    ["prop1"]=>
    string(4) "val1"
    ["prop2"]=>
    string(4) "val2"
  }
  [1]=>
  object(stdClass)#2 (2) {
    ["prop1"]=>
    string(4) "val1"
    ["prop2"]=>
    string(4) "val2"
  }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement