This problem often occurs at work. I get a two-dimensional array, but the array only contains id and name. For example, this array is like this: This problem is often encountered at work.
I get a two-dimensional array, but the array only contains id and name. For example, the array is like this:
$ Array = array ('id' => a, 'name' => 'hy369'), array ('id' => B, 'name' => 'php blog'), array ('id' => c, 'name' => 'emlog '),);
Sometimes we need to use this array to obtain a new array like the following:
Sometimes we need to use this array to get a new array like the following: $ newArray = array ('hy369', 'php blog', 'emlog ',);
At this time, a foreach is usually used for dimensionality reduction. I don't know what your friends are like. I used to do this before hybri369.
However, I found that PHP5.5 has a function specifically for this requirement: array_column.
We only need to call this method to get the results we need:
array_column($array, 'name');
This function has a more convenient function. if we pass the third parameter, for example:
array_column($array, 'test', 'id');
The following result is displayed:
$ NewArray = array ('a' => 'hy369', 'B' => 'php blog', 'C' => 'emlog ',);
What do you think? I'm drunk, but it's not so refreshing.
But there is a problem. As I mentioned earlier, this is only supported by php5.5.
However, the power of the people is infinite and there are already compatibility methods for earlier versions:
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) { $result[] = $item[$column_key]; } else { $result[$item[$index_key]] = $item[$column_key]; } return $result; }, []); }}
Note that the version I provided here only supports 5.3 and above, because the anonymous function method, that is, the function use method, is supported from 5.3, if you want to be compatible with earlier versions, you can use the following methods on the Internet:
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 an omnipotent method. although foreach is also used, it is easier to create a function independently than to use foreach separately each time.
The above is the content of the sharp array_column function in the note 006. For more information, see The PHP Chinese website (www.php1.cn )!