Mapping Nested Object Values Into A Single Array In PHP

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

The content of this field is kept private and will not be shown publicly.
CAPTCHA
11 + 7 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.