首页 >后端开发 >php教程 > 正文

php返回数组中指定的一列(php5.5.0默认函数array_column()在php<5.5.0的应用)

原创2016-07-25 09:12:090568
array_column() 返回数组中指定键名的列
(PHP 5 >= 5.5.0)
array_column — 返回数组中指定的一列
php参考手册:http://www.php.net/manual/zh/function.array-column.php

如果php版本小于5.5.0怎么办呢?我们自定义一个
以下代码摘自onethink
  1. /**
  2. * 返回数组中指定的一列
  3. * http://www.onethink.cn
  4. * /Application/Common/Common/function.php
  5. *
  6. * array_column — PHP 5 >= 5.5.0 默认函数
  7. * PHP 5 < 5.5.0 则使用自定义函数
  8. *
  9. * @access public
  10. * @param array $input 需要取出数组列的多维数组(或结果集)
  11. * @param string $columnKey 需要返回值的列,它可以是索引数组的列索引,或者是关联数组的列的键。也可以是NULL,此时将返回整个数组(配合indexKey参数来重置数组键的时候,非常管用)
  12. * @param string $indexKey 作为返回数组的索引/键的列,它可以是该列的整数索引,或者字符串键值。
  13. * @return array
  14. */
  15. if (! function_exists('array_column'))
  16. {
  17. function array_column(array $input, $columnKey, $indexKey = null)
  18. {
  19. $result = array();
  20. if (null === $indexKey)
  21. {
  22. if (null === $columnKey)
  23. {
  24. $result = array_values($input);
  25. }
  26. else
  27. {
  28. foreach ($input as $row)
  29. {
  30. $result[] = $row[$columnKey];
  31. }
  32. }
  33. }
  34. else
  35. {
  36. if (null === $columnKey)
  37. {
  38. foreach ($input as $row)
  39. {
  40. $result[$row[$indexKey]] = $row;
  41. }
  42. }
  43. else
  44. {
  45. foreach ($input as $row)
  46. {
  47. $result[$row[$indexKey]] = $row[$columnKey];
  48. }
  49. }
  50. }
  51. return $result;
  52. }
  53. }
复制代码
  1. // Array representing a possible record set returned from a database
  2. $records = array(
  3. array(
  4. 'id' => 2135,
  5. 'first_name' => 'John',
  6. 'last_name' => 'Doe',
  7. ),
  8. array(
  9. 'id' => 3245,
  10. 'first_name' => 'Sally',
  11. 'last_name' => 'Smith',
  12. ),
  13. array(
  14. 'id' => 5342,
  15. 'first_name' => 'Jane',
  16. 'last_name' => 'Jones',
  17. ),
  18. array(
  19. 'id' => 5623,
  20. 'first_name' => 'Peter',
  21. 'last_name' => 'Doe',
  22. )
  23. );
  24. $first_names = array_column($records, 'first_name');
  25. print_r($first_names);
  26. ?>
复制代码
  1. Array
  2. (
  3. [0] => John
  4. [1] => Sally
  5. [2] => Jane
  6. [3] => Peter
  7. )
复制代码
php中文网最新课程二维码

声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理

相关文章

相关视频


网友评论

文明上网理性发言,请遵守 新闻评论服务协议

我要评论
  • 专题推荐

    作者信息

    php中文网

    认证0级讲师

    推荐视频教程
  • javascript初级视频教程javascript初级视频教程
  • jquery 基础视频教程jquery 基础视频教程
  • 视频教程分类