How to convert multiple object into array in php

Whilst trying to transform multiple objects and put them into one array I unfortunately get a array-in-array result.

The objects I would like to transform:

array[2] {
  [0]=>
  object[stdClass]#104 [1] {
    ["name"]=>
    string[4] "Paul"
  }
  [1]=>
  object[stdClass]#105 [1] {
    ["name"]=>
    string[5] "Jenna"
  }
}

My PHP:

for [$i=0; $i < count[$readers] ; $i++] {
    $json = json_encode[$readers[$i]];    // 1          

    $data = json_decode[$json, TRUE];     // 2    

    $arr = array[];
    array_push[$arr, $data];              // 3
}

The outputs:

// 1
{"name":"Paul"}{"name":"Jenna"}

-

// 2
Array
[
    [name] => Paul
]
Array
[
    [name] => Jenna
]

-

// 3
Array
[
    [0] => Array
        [
            [name] => Paul
        ]

]
Array
[
    [0] => Array
        [
            [name] => Jenna
        ]

]  

Desired Outcome

I would like to have everything merged into one array. The key is the index and the value is the name.

Array
[
    [0] => Paul
    [1] => Jenna
]

B. Desai

16.3k5 gold badges24 silver badges46 bronze badges

asked Nov 5, 2017 at 10:34

Loop through the array of objects [$arr] and compile the final array [$finArr] with the $val->string value. Try this:

$finArr = array[];
foreach [$arr as $key => $val] {
  $finArr[] = $val->string;
}

answered Nov 5, 2017 at 10:37

You can simply iterate through the array of readers, pull out the name of each reader, and add each of their names to a numerically indexed array as you desire.

$names = array[]; // Initialize.

foreach[$readers as $reader] {
    if [!empty[$reader->name]] {
        $names[] = $reader->name;
    }
}
print_r[$names]; // To see what you've got.
Array
[
    [0] => Paul
    [1] => Jenna
]

answered Nov 5, 2017 at 10:39

jaswrksjaswrks

1,23510 silver badges13 bronze badges

You have to extract key also from array. And declare $arr = array[] outside foreach

$arr = array[];
for [$i=0; $i < count[$readers] ; $i++] {
    $data = $readers[$i]->name;          //change this line 
    array_push[$arr, $data];              // 3
}

print_r[$arr];

Another way is you can simply use array_column[]

$arr = array_column[$readers,"name"];
print_r[$arr];

answered Nov 5, 2017 at 10:38

B. DesaiB. Desai

16.3k5 gold badges24 silver badges46 bronze badges

Introduction to PHP object to array

The following article provides an outline for PHP object to array. As we all know, object is known as a class instance which has memory allocated. In the case of an array, it is a data structure containing one or more values of a similar type in a single name. On the other hand, an associative array is not like a normal PHP array. An associative array is an array that consists of a string index which stores item values linked with key values other than in order of the linear index.

Methods of a PHP object to array

Now, let us see different ways in which we can convert PHP object to array.

Method 1 – With the help of the json_decode and json_encode method.

In this method, the function json_decode takes JSON encoded string and changes it into a PHP variable, whereas the json_encode function returns a string which is encoded in a json format for a particular value.

Syntax:

$arr = json_decode[json_encode [ $obj ] , true];

Method 2 – With the help of type casting.

Typecasting is a technique in which one data type variable into the another data type. It is considered as an explicit data type conversion. It can translate a PHP object to an array with the help of typecasting rules in PHP.

Syntax:

$arr = [array] $obj;

How to Convert object to array in PHP?

As we all know, there are several formats of data like strings, objects, arrays etc. In the case of PHP also, there are data formats like this. In order to get the needed output, a php object obj result is needed in a format of an associative array.

Now, let us see how to translate a php object.

Code:

This is the skeleton for converting an object into an array.

Now let us see how to perform this.

  • In order to encode the string, use “object = json_encode[$array];”

When the object is var_dump, all items will be displayed.

  • For decoding into an object, a json string which is available will be used to convert and string formatting is done to an object. It will be done using $obj = json_decode[json_encode[$arr]];
  • When the object is var_dump, all items will be displayed after converting into an array.

Here, one important point to consider is json_decode that translates a json string to an object, except you offer another option that is boolean which can be true or false. Even if the second parameter is considered as true, an array will be obtained.

Also, when json encode operation and decode operation are used, arrays are converted to objects that take up many resources if the array is large. In that case, the better method to type cast an array to an object that uses the object cast.

Consider $obj = [object] $arr; syntax. Here also, object will be converted into arrays.

Based on the requirements, you can choose the method you want for the conversion of an array into an object in PHP.

Examples of a PHP object to array

Different examples are mentioned below:

Example #1

PHP program to convert an object to an array using the typecasting method.

Code:

Output:

In this program, a class hospital is created, and inside that, three elements such as el1, el2, and el3. Then, a __construct[] function is declared, which gets executed during the time object is created. Once this is done, the constructor takes parameters that are later offered during the object creation using the keyword “new”. From the program, it can be seen that objects get printed in the first case of expression var_dump[]. But in the second case of expression, an object is casted into an array using the typecasting procedure.

Example #2

PHP program to convert an object to an array using json encode and json decode.

Code:

Output:

In this program also, a class hospital is created, and inside that, two elements such as el1 and el2, are created. Then, a __construct[] function is declared, which gets executed during the time object is created. Once this is done, the constructor takes parameters that are later offered during the object creation using the keyword “new”. From the program, it can be seen that objects get printed in the first case of expression var_dump[]. But in the second case of expression, an object is casted into an array using the typecasting procedure. Here, the first method in the method sections is used for converting an object into an array.

Conclusion

An associative array is an array that consists of a string index which stores item values linked with key values other than in order of the linear index. This article saw how PHP object to array is working, methods to achieve it, and different examples.

Recommended Articles

This is a guide to PHP object to array. Here we discuss the introduction, methods, how to convert object to array in PHP? and examples respectively. You may also have a look at the following articles to learn more –

  1. PHP delete file
  2. PHP array_pop[]
  3. PHP implode
  4. PHP Include and Require

How to convert objects into array in PHP?

Converting an object to an array with typecasting technique: php class bag { public function __construct[ $item1, $item2, $item3]{ $this->item1 = $item1; $this->item2 =$item2; $this->item3 = $item3; } } $myBag = new bag["Books", "Ball", "Pens"]; echo "Before conversion :".

How to convert multidimensional object to array in PHP?

You may need to make it to be neater. ... .
A slightly neater approach for this common request: function objectToArray[$data] { if [is_object[$data]] { $data = get_object_vars[$data]; } if [is_array[$data]] { return array_map[FUNCTION, $data]; } else { return $data; } } ... .
hello @SubRed, your answer seems helpful to me!.

How do you change an object to an array?

To convert an object to an array you use one of three methods: Object. keys[] , Object. values[] , and Object. entries[] .

How do you object in PHP?

Define Objects Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values. Objects of a class is created using the new keyword.

Chủ Đề