Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Yii2 - Quickly add a property to an array using ArrayHelper::getColumn
<?php
require(__DIR__ . '/vendor/autoload.php');
use yii\helpers\ArrayHelper;
use yii\helpers\VarDumper;
$fooArray = [
['name' => 'Han Solo', 'email' => 'han.solo@starwars.com'],
['name' => '', 'email' => 'luc.skywalker@starwars.com'],
['name' => 'Obi-Wan Kenobi', 'email' => 'obiwan.kenobi@starwars.com']
];
$barArray = ArrayHelper::getColumn($fooArray, function ($element) {
$element['displayname'] = empty($element['name']) ? $element['email'] : $element['name'];
return $element;
});
VarDumper::dump($barArray);
// Output:
// [ 0 => [ 'name' => 'Han Solo' 'email' => 'han.solo@starwars.com' 'displayname' => 'Han Solo' ] 1 => [ 'name' => '' 'email' => 'luc.skywalker@starwars.com' 'displayname' => 'luc.skywalker@starwars.com' ] 2 => [ 'name' => 'Obi-Wan Kenobi' 'email' => 'obiwan.kenobi@starwars.com' 'displayname' => 'Obi-Wan Kenobi' ] ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.