Use the array_map() function to extract values from a complex object structure into a single array without using a loop.
<?php
class Outer {
public Inner $inner;
public function __construct($inner) {
$this->inner = $inner;
}
}
class Inner {
public int $value;
public function __construct($value) {
$this->value = $value;
}
}
$objects = [];
$objects[] = new Outer(new Inner(1));
$objects[] = new Outer(new Inner(2));
$objects[] = new Outer(new Inner(3));
$objects[] = new Outer(new Inner(4));
$objects[] = new Outer(new Inner(5));
$values = array_map(function($object) {return $object->inner->value;}, $objects);
print_r($values);
This produces the following output.
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Add new comment