Converted a two-dimensional array to an object in PHP. How to access the values?

0

Hello, I have the following array:

$array[0]["nome"] = "nome exemplo";
$array[0]["idade"] = "idade exemplo";
$array[1]["nome"] = "nome exemplo 2";
$array[0]["idade"] = "idade exemplo 2";

I created an object of this array:

$obj = (object) $array;

I would like to know how to access these values with this object, when the array has only one dimension I simply make $ obj-> name, but when it has two dimensions?

    
asked by anonymous 20.04.2016 / 19:45

2 answers

1

As @rray said in your comment

  

You can even set numerical properties on an object but you can not access them. That's the problem.

Using the get_object_vars feature is clear:

var_dump(get_object_vars($obj));
array(0) {
}

In other words, it did not generate any attributes in the class, but only 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;

So you're reversing 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 see, it does not make much sense to do this because, since you have multiple name values, you will still have an array.

    
20.04.2016 / 20:40
0

There is no good reason to do this conversion, but to be able to capture the elements of cast of the array, you need to convert it to an accessible element, one of the ways to do this is to use json_encode() and json_decode() , there are also other ways to do this, for example: $data = get_object_vars($obj); and extract($data); , a priori, for what you need, the example below already works:

$array = array();
$array[0]["nome"] = "nome exemplo";
$array[0]["idade"] = "idade exemplo";
$array[1]["nome"] = "nome exemplo 2";
$array[0]["idade"] = "idade exemplo 2";

$obj = (object) $array;
$extractObj = json_decode(json_encode($obj));

echo $extractObj->{0}->nome;

To see the structure of your object, use the function var_dump($obj) .

See this demo on Ideone

    
20.04.2016 / 21:05