PHP - Transforming object into array

Asked

Viewed 12,763 times

1

I need to transform an object into an array to be able to traverse it and extract its data, even with you:

   $array = (array) $object;

But the result with a var_dump($array) Here’s the thing, so I can’t walk 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 intend to go 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 the return: Clientedata: Array

  • How are you traversing this array? If possible [Edit] your question and add your code.

  • 1

    From what I saw and multidimensional. The foreach will go through the first dimension. If you want to go through the second dimension you must place foreach inside foreach. It’s so on. Or specify the dimension you want to navigate by informing the key to the dimension.

  • What I don’t understand is why, since if I create an object with stdClass and turn it into an array I can run it normally.

  • What happens in this error is that the first dimension does not contain values to be printed as string. You must now enter the second dimension. There you asked to print the $key it even prints. More $value is another array. That is the second dimension. For you to view it you must do so print_r($value) or var_dump($value).

  • But regardless of why, I managed to traverse the "second dimension" with another foreach.

  • But because this first dimension is created?

  • I don’t know where you’re getting this data from. But this is used a lot when you want to separate data by dimensions. Type in first dimension has number of work orders. There in the second dimension can have N array containing the identification of each customer data, order data, company data and in the third dimension can have the data of each of the items of the second dimension as customer name, Cpf, etc. understood?

  • I get it, thank you.

  • Now that I’ve seen it. Access the data as follows. echo $value->name; echo $value->email; And you can foreach without key as well. Type foreach($array as $a){ echo $a->name; }

  • This is not a collection for you to browse!

Show 5 more comments

5 answers

2

You can use the function get_object_vars it returns all public properties of a given object in the format of array associative.

$foo = get_object_vars($object);

var_dump($foo);
// Resultado
array(3) {
    ["nome"]=>
    string(4) "Nome"
    ["email"]=>
    string(19) "[email protected]"
    ["celular"]=>
    string(15) "(00) 00000-0000"
}

0

To traverse a multidimensional array just use was foreach, or pass the index on foreach. Ex:

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

If you don’t know the name of the index, just 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 receiving this multidimensional array because your object must be storing these values in the variable Clientedata. 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 );

-1

But in case, you don’t have a collection to go through, so you can’t go through it, to access the data after converting into array would just do this:

echo $array["Clientedata"]["nome"] . '\n<br>' .
     $array["Clientedata"]["email"] . '\n<br>' .
     $array["Clientedata"]["celular"];

To access directly from the object:

echo $objeto->Clientedata->nome . '\n<br>' .
     $objeto->Clientedata->email . '\n<br>' .
     $objeto->Clientedata->celular;

If Clientedata were a collection, you could make these two forms:

a) You wouldn’t necessarily need to convert it to array to go through it, but if you prefer to go through it in array mode, just do so:

 $array = (array) $objeto;
    
    if (count($array['Clientedata'])) {
        foreach($array['Clientedata'] as $key => $value){
            echo  $value['nome'] . '<br>\n';
            echo  $value['email'] . '<br>\n';
            echo $value['celular'];
        }
    }

b) In the case of object, it is only to make a Countable implement in its class:

//No php 7, essa função deve existir, mas se não existir ela é criada abaixo:
    if (!function_exists('is_countable')) {
        function is_countable($value): bool
        {
           return is_array($value) || (is_object($value) && $value instanceof Countable);
        }
     }
       //então vc checa se o elemento possui uma coleção: 
       if (is_contable($objeto->Clientedata)) {
           //e percorre ele...
           foreach( $objeto->Clientedata as $key => $value){
                echo  $value->nome . '<br>\n';
                echo  $value->email. '<br>\n';
                echo $value->celular;
            }
       }
    }

-1

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

$meuArray = json_decode($object,true);
  • This will not work because the function json_decode receives a string as first parameter.

-3

Simple and practical...

foreach($array as $element){
    $result[$element[Clientedata]][] = $element;
}

$data[];
foreach($result as $key=>$value){
   $data[] = ['Clientedata' => $key,
             'item' =>$value
       ];
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.