Such problems are often encountered in the work.
I get a two-dimensional array, but the array contains only the ID and name. For example, this array is like this:
$array = array (' ID ' =>a, ' name ' = ' Hy369 '), array (' ID ' =>b, ' name ' = ' PHP blog '), array (' ID ' =>c, ' name ' (= ' emlog '),);
Sometimes we need this array to get a new array like this:
Sometimes we will need this array to get a new array like this: $newArray = Array ( ' Hy369 ', ' PHP blog ', ' emlog ');
At this time, the general will use a foreach to dimensionality reduction. I do not know what friends are like, anyway Hy369 used to do so often.
Finally, however, I found out that the PHP5.5 version had a function specifically for that requirement: Array_column.
We just call it so we can get the results we need:
Array_column ($array, ' name ');
This function also has a more convenient function, if we pass the third argument, for example:
Array_column ($array, ' Test ', ' id ');
You will get the result:
$newArray = Array ( ' a ' => ' Hy369 ', ' B ' => ' PHP blog ', ' C ' => ' Emlog ',);
What do you think, anyway I was drunk, this is not the general cool AH.
However, there is a problem, I have mentioned earlier, this will be supported by the beginning of the php5.5 version.
However, the power of the people is endless, there is already a low version of the compatibility method:
if (!function_exists (' Array_column ')) { function array_column ($array, $column _key, $index _key = null) { Return Array_reduce ($array, function ($result, $item) use ($column _key, $index _key) { if (null = = = $index _key) { c8/> $result [] = $item [$column _key]; } else { $result [$item [$index _key]] = $item [$column _key]; } return $result;} , []);} }
Note, however, that the version I provide here only supports 5.3 and above, because the way in which anonymous functions, that is, function use, is supported from 5.3, and if you want to be compatible with a lower version, there is a corresponding method on the Web:
if (!function_exists (' Array_column ')) { function Array_column (array $array, $columnKey, $indexKey = null) { $result = Array (); foreach ($array as $subArray) { if (!is_array ($subArray)) { continue; } elseif (Is_null ($indexKey) & ;& Array_key_exists ($columnKey, $subArray)) { $result [] = $subArray [$columnKey]; } elseif (Array_key_exists ($ Indexkey, $subArray)) { if (Is_null ($columnKey)) { $result [$subArray [$indexKey]] = $subArray; } elseif ( Array_key_exists ($columnKey, $subArray)) { $result [$subArray [$indexKey]] = $subArray [$columnKey]; } } } return $result; }}
This is definitely a panacea, although it also uses a foreach, but independent into a function, but also more than a single time to use the foreach more convenient.
The above is the note 006 Sharp array_column function content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!