PHP - Transform object into array

0

I need to transform an object into an array so I can navigate through it and extract its data, even with:

   $array = (array) $object;

But the result with a var_dump($array) is as follows, so I can not traverse it with a foreach :

array(1) {
  ["Clientedata"]=>
  array(3) {
    ["nome"]=>
    string(4) "Nome"
    ["email"]=>
    string(19) "[email protected]"
    ["celular"]=>
    string(15) "(00) 00000-0000"
  }
}

I want to loop through the array as follows:

    foreach($array as $key => $value){
        echo "$key: $value";
    }

So I just get an error: Notice: Array to string conversion in ... And return: Clientedata: Array

    
asked by anonymous 14.02.2018 / 02:38

2 answers

0

To go through a multidimensional array, just use foreach , or pass index in foreach . Ex:

foreach($array['Clientedata'] as $key => $value){
    echo "$key: $value";
}

If you do not know the name of the index, simply use the function end or reset to capture the last or first element of the array respectively.

$novoArray = reset($array);

foreach($novoArray as $key => $value){
    echo "$key: $value";
}

You are probably getting this multidimensional array because your object must be storing these values in the Clientedata variable. Ex:

<?php

class Cliente {
    public $Clientedata;

    public function __construct($nome, $email, $celular) {
        $this->Clientedata = [
            "nome"    => $nome,
            "email"   => $email,
            "celular" => $celular,
        ];
    }
}

$obj = new Cliente("Cliente", "[email protected]", "123456789");

var_dump( (array) $obj );
    
14.02.2018 / 03:17
-1

To transform an object into array we can use the function json_decode() passing the second parameter as true which it automatically converts to an array. would look something like

$meuArray = json_decode($object,true);
    
14.02.2018 / 03:44