Created
September 2, 2013 17:53
-
-
Save noganno/6415507 to your computer and use it in GitHub Desktop.
аналог array_column
URL: http://habrahabr.ru/post/173943/ Формат вызова: (array) array_column(array $input, mixed $columnKey[, mixed $indexKey]); Здесь $input — исходный [N>1]-мерный массив, из которого производится выборка, а $columnKey — индекс столбца, по которому она делается. Если будет указан параметр $indexKey, результат будет дополнитель…
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
function array_column ($input, $columnKey, $indexKey = null) { | |
if (!is_array($input)) { | |
return false; | |
} | |
if ($indexKey === null) { | |
foreach ($input as $i => &$in) { | |
if (is_array($in) && isset($in[$columnKey])) { | |
$in = $in[$columnKey]; | |
} else { | |
unset($input[$i]); | |
} | |
} | |
} else { | |
$result = array(); | |
foreach ($input as $i => $in) { | |
if (is_array($in) && isset($in[$columnKey])) { | |
if (isset($in[$indexKey])) { | |
$result[$in[$indexKey]] = $in[$columnKey]; | |
} else { | |
$result[] = $in[$columnKey]; | |
} | |
unset($input[$i]); | |
} | |
} | |
$input = &$result; | |
} | |
return $input; | |
} | |
$records = array( | |
array( | |
'id' => 2135, | |
'first_name' => 'John', | |
'last_name' => 'Doe' | |
), | |
array( | |
'id' => 3245, | |
'first_name' => 'Sally', | |
'last_name' => 'Smith' | |
), | |
array( | |
'id' => 5342, | |
'first_name' => 'Jane', | |
'last_name' => 'Jones' | |
), | |
array( | |
'id' => 5623, | |
'first_name' => 'Peter', | |
'last_name' => 'Doe' | |
) | |
); | |
$firstNames = array_column($records, 'first_name'); | |
print_r($firstNames); | |
Array | |
( | |
[0] => John | |
[1] => Sally | |
[2] => Jane | |
[3] => Peter | |
) | |
$lastNames = array_column($records, 'last_name', 'id'); | |
print_r($lastNames); | |
Array | |
( | |
[2135] => Doe | |
[3245] => Smith | |
[5342] => Jones | |
[5623] => Doe | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment