Skip to content

Instantly share code, notes, and snippets.

@awarrenlove
Created June 29, 2018 15:32
Show Gist options
  • Save awarrenlove/faa8a9f497e2d839528360f3e793ad94 to your computer and use it in GitHub Desktop.
Save awarrenlove/faa8a9f497e2d839528360f3e793ad94 to your computer and use it in GitHub Desktop.
PHP array_map_keys
<?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