How can I convert an array like this to an object?
[128] => Array
(
[status] => "Figure A.
Facebook\'s horizontal scrollbars showing u
Obviously just an extrapolation of some other folks' answers, but here's the recursive function that will convert any mulch-dimensional array into an object:
function convert_array_to_object($array){
$obj= new stdClass();
foreach ($array as $k=> $v) {
if (is_array($v)){
$v = convert_array_to_object($v);
}
$obj->{strtolower($k)} = $v;
}
return $obj;
}
And remember that if the array had numeric keys they can still be referenced in the resulting object by using {}
(for instance: $obj->prop->{4}->prop
)
You could also use an ArrayObject, for example:
<?php
$arr = array("test",
array("one"=>1,"two"=>2,"three"=>3),
array("one"=>1,"two"=>2,"three"=>3)
);
$o = new ArrayObject($arr);
echo $o->offsetGet(2)["two"],"\n";
foreach ($o as $key=>$val){
if (is_array($val)) {
foreach($val as $k => $v) {
echo $k . ' => ' . $v,"\n";
}
}
else
{
echo $val,"\n";
}
}
?>
//Output:
2
test
one => 1
two => 2
three => 3
one => 1
two => 2
three => 3
I also had this issue, but I noticed that json_decode converts JSON array to object.
So, I came about my solution by using json_encode($PHPArray) which returns A JSON string of object, then I decoded the string with Json_decode($string) and it would return a perfectly structured object. Shorthand
$object = json_decode(json_encode($array));
Or
$jsonString = json_encode($array);
$object = json_decode($jsonString);
Little complicated but easy to extend technique:
Suppose you have an array
$a = [
'name' => 'ankit',
'age' => '33',
'dob' => '1984-04-12'
];
Suppose you have have a Person class which may have more or less attributes from this array. for example
class Person
{
private $name;
private $dob;
private $age;
private $company;
private $city;
}
If you still wanna change your array to the person object. You can use ArrayIterator Class.
$arrayIterator = new \ArrayIterator($a); // Pass your array in the argument.
Now you have iterator object.
Create a class extending FilterIterator Class; where you have to define the abstract method accept. Follow the example
class PersonIterator extends \FilterIterator
{
public function accept()
{
return property_exists('Person', parent::current());
}
}
The above impelmentation will bind the property only if it exists in the class.
Add one more method in the class PersonIterator
public function getObject(Person $object)
{
foreach ($this as $key => $value)
{
$object->{'set' . underscoreToCamelCase($key)}($value);
}
return $object;
}
Make sure you have mutators defined in your class. Now you are ready to call these function where you want to create object.
$arrayiterator = new \ArrayIterator($a);
$personIterator = new \PersonIterator($arrayiterator);
$personIterator->getObject(); // this will return your Person Object.
I would definitly go with a clean way like this :
<?php
class Person {
private $name;
private $age;
private $sexe;
function __construct ($payload)
{
if (is_array($payload))
$this->from_array($payload);
}
public function from_array($array)
{
foreach(get_object_vars($this) as $attrName => $attrValue)
$this->{$attrName} = $array[$attrName];
}
public function say_hi ()
{
print "hi my name is {$this->name}";
}
}
print_r($_POST);
$mike = new Person($_POST);
$mike->say_hi();
?>
if you submit:
you will get this:
I found this more logical comparing the above answers from Objects should be used for the purpose they've been made for (encapsulated cute little objects).
Also using get_object_vars ensure that no extra attributes are created in the manipulated Object (you don't want a car having a family name, nor a person behaving 4 wheels).
This function works as same as json_decode(json_encode($arr), false)
.
function arrayToObject(array $arr)
{
$flat = array_keys($arr) === range(0, count($arr) - 1);
$out = $flat ? [] : new \stdClass();
foreach ($arr as $key => $value) {
$temp = is_array($value) ? $this->arrayToObject($value) : $value;
if ($flat) {
$out[] = $temp;
} else {
$out->{$key} = $temp;
}
}
return $out;
}
$arr = ["a", "b", "c"];
var_export(json_decode(json_encode($arr)));
var_export($this->arrayToObject($arr));
Output:
array(
0 => 'a',
1 => 'b',
2 => 'c',
)
array(
0 => 'a',
1 => 'b',
2 => 'c',
)
$arr = [["a" => 1], ["a" => 1], ["a" => 1]];
var_export(json_decode(json_encode($arr)));
var_export($this->arrayToObject($arr));
Output:
array(
0 => stdClass::__set_state(array('a' => 1,)),
1 => stdClass::__set_state(array('a' => 1,)),
2 => stdClass::__set_state(array('a' => 1,)),
)
array(
0 => stdClass::__set_state(array('a' => 1,)),
1 => stdClass::__set_state(array('a' => 1,)),
2 => stdClass::__set_state(array('a' => 1,)),
)
$arr = ["a" => 1];
var_export(json_decode($arr));
var_export($this->arrayToObject($arr));
Output:
stdClass::__set_state(array('a' => 1,))
stdClass::__set_state(array('a' => 1,))