Created
June 29, 2018 15:32
-
-
Save awarrenlove/faa8a9f497e2d839528360f3e793ad94 to your computer and use it in GitHub Desktop.
PHP array_map_keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function array_map_keys( | |
Closure $keys, | |
Closure $values, | |
array $array | |
): array { | |
$output = []; | |
foreach ($array as $value) { | |
$output[$keys($value)] = $values($value); | |
} | |
return $output; | |
} | |
$input = [ | |
(object) [ | |
'id' => 1, | |
'color' => 'red', | |
'item' => 'apple', | |
], | |
(object) [ | |
'id' => 2, | |
'color' => 'orange', | |
'item' => 'orange', | |
], | |
(object) [ | |
'id' => 3, | |
'color' => 'white', | |
'item' => 'eggplant', | |
], | |
]; | |
$output = array_map_keys( | |
function($val) { | |
return $val->id; | |
}, | |
function($val) { | |
return $val; | |
}, | |
$input | |
); | |
/* | |
* Array | |
* ( | |
* [1] => stdClass Object | |
* ( | |
* [id] => 1 | |
* [color] => red | |
* [item] => apple | |
* ) | |
* | |
* [2] => stdClass Object | |
* ( | |
* [id] => 2 | |
* [color] => orange | |
* [item] => orange | |
* ) | |
* | |
* [3] => stdClass Object | |
* ( | |
* [id] => 3 | |
* [color] => white | |
* [item] => eggplant | |
* ) | |
* | |
* ) | |
*/ | |
print_r($output); | |
$output = array_map_keys( | |
function($val) { | |
return $val->id; | |
}, | |
function($val) { | |
return $val->color; | |
}, | |
$input | |
); | |
/* | |
* Array | |
* ( | |
* [1] => red | |
* [2] => orange | |
* [3] => white | |
* ) | |
*/ | |
print_r($output); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment