This package provides the object_column() function, which works similarly to the array_column() function of the standard library, but having the ability to work with objects.
To search for columns in objects, both the public properties of these objects and the methods getColumnName() / hasColumnName() / isColumnName() / columnName() (in that exact order), as well as by the methods of the ArrayAccess interface.
Function object_column() is fully backward compatible with array_column() and can work with regular arrays the same way.
In addition, the object_column() function supports call chainings.
You need:
- PHP >= 7.1.0 but the latest stable version of PHP is recommended
Via Composer
$ composer require cryonighter/object-column
The function works as follows:
use function Cryonighter\ObjectColumn\object_column;
$objects = [
new class {
public $foo = '123';
public $bar = '456';
public $baz = '789';
},
new class {
public $foo = 'qwe';
public $bar = 'asd';
public $baz = 'zxc';
},
];
$result = object_column($objects, 'foo', 'bar');
use function Cryonighter\ObjectColumn\object_column;
$objects = [
new class {
public function getFoo() {
return new class {
public function baz(): string {
return '123';
}
};
}
public function getBar() {
return new class {
public function buz(): string {
return '456';
}
};
}
},
new class {
public function getFoo() {
return new class {
public function baz(): string {
return 'qwe';
}
};
}
public function getBar() {
return new class {
public function buz(): string {
return 'asd';
}
};
}
},
];
$result = object_column($data, 'foo.baz', 'bar.buz');
use function Cryonighter\ObjectColumn\object_column;
$objects = [
new ArrayObject([
'foo' => new ArrayObject(['baz' => '123']),
'bar' => new ArrayObject(['buz' => '456']),
]),
new ArrayObject([
'foo' => new ArrayObject(['baz' => 'qwe']),
'bar' => new ArrayObject(['buz' => 'asd']),
]),
];
$result = object_column($data, 'foo.baz', 'bar.buz');
In all cases, the result will be the same
[456 => '123', 'asd' => 'qwe']
Also, the function can be used to index an array, for this it is enough not to pass the first argument
use function Cryonighter\ObjectColumn\object_column;
$objects = [
[
'foo' => ['baz' => '123'],
'bar' => ['buz' => '456'],
],
[
'foo' => ['baz' => 'qwe'],
'bar' => ['buz' => 'asd'],
],
];
$result = object_column($data, null, 'bar.buz');
[
'456' => [
'foo' => ['baz' => '123'],
'bar' => ['buz' => '456'],
],
'asd' => [
'foo' => ['baz' => 'qwe'],
'bar' => ['buz' => 'asd'],
],
];
If no second or third argument is passed to the function, the original array will be returned. This operation is meaningless.
Please see CHANGELOG for more information on what has changed recently.
$ php vendor/phpunit/phpunit/phpunit tests
Please see CONTRIBUTING and CODE_OF_CONDUCT for details.
If you discover any security related issues, please email cryonighter@yandex.ru
instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.