As @rray said in their comment
You can even define numeric properties on an object but you can’t access them this is the problem.
Using the functionality of get_object_vars
that is very clear:
var_dump(get_object_vars($obj));
array(0) {
}
In other words, it did not generate any attribute in the class, but just doing :
var_dump($obj);
object(stdClass)#48 (2) {
[0]=>
array(2) {
["nome"]=>
string(12) "nome exemplo"
["idade"]=>
string(13) "idade exemplo"
}
[1]=>
array(2) {
["nome"]=>
string(14) "nome exemplo 2"
["idade"]=>
string(15) "idade exemplo 2"
}
}
Possible solution
$array[0]["nome"] = "nome exemplo";
$array[0]["idade"] = "idade exemplo";
$array[1]["nome"] = "nome exemplo 2";
$array[1]["idade"] = "idade exemplo 2";
foreach ($array as $k => $attributes){
foreach ($attributes as $attribute => $value) {
$array[$attribute][$k] = $value;
unset($array[$k]);
}
}
$obj = (object) $array;
This way you will be inverting the order and generating an associative array. Which in the conversion generates attributes in the class.
var_dump(get_object_vars($obj));
array(2) {
["nome"]=>
array(2) {
[0]=>
string(12) "nome exemplo"
[1]=>
string(14) "nome exemplo 2"
}
["idade"]=>
array(2) {
[0]=>
string(13) "idade exemplo"
[1]=>
string(15) "idade exemplo 2"
}
}
However as you can notice it doesn’t make much sense to make this conversion since as you have several name values you will still have an array.
Converting an array that is not associative to an object is not a good idea. If it was an associative array, just call the properties, in sequence. Here is a response where several examples are presented, and suggestions of how to proceed in this case. http://stackoverflow.com/questions/10333016/how-to-access-object-properties-with-names-like-integers
– mau humor
You can even define numerical properties on an object but you can’t access them this is the problem, you need to change the way to address the problem.
– rray