PHP Transform multiple objects into one array

Magiranu asked
php arrays object
via

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
)


Answer
via

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
)
Share This
Posted in: