首页 >后端开发 >php教程 >php自定义数组函数array_column

php自定义数组函数array_column

WBOY
WBOY原创
2016-07-25 08:54:331318浏览
  1. if(!function_exists('array_column')){
  2. function array_column($input, $columnKey, $indexKey=null){
  3. $columnKeyIsNumber = (is_numeric($columnKey)) ? true : false;
  4. $indexKeyIsNull = (is_null($indexKey)) ? true : false;
  5. $indexKeyIsNumber = (is_numeric($indexKey)) ? true : false;
  6. $result = array();
  7. foreach((array)$input as $key=>$row){
  8. if($columnKeyIsNumber){
  9. $tmp = array_slice($row, $columnKey, 1);
  10. $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null;
  11. }else{
  12. $tmp = isset($row[$columnKey]) ? $row[$columnKey] : null;
  13. }
  14. if(!$indexKeyIsNull){
  15. if($indexKeyIsNumber){
  16. $key = array_slice($row, $indexKey, 1);
  17. $key = (is_array($key) && !empty($key)) ? current($key) : null;
  18. $key = is_null($key) ? 0 : $key;
  19. }else{
  20. $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
  21. }
  22. } // bbs.it-home.org
  23. $result[$key] = $tmp;
  24. }
  25. return $result;
  26. }
  27. }
  28. // 使用例子
  29. $records = array(
  30. array(
  31. 'id' => 2135,
  32. 'first_name' => 'John',
  33. 'last_name' => 'Doe'
  34. ),
  35. array(
  36. 'id' => 3245,
  37. 'first_name' => 'Sally',
  38. 'last_name' => 'Smith'
  39. ),
  40. array(
  41. 'id' => 5342,
  42. 'first_name' => 'Jane',
  43. 'last_name' => 'Jones'
  44. ),
  45. array(
  46. 'id' => 5623,
  47. 'first_name' => 'Peter',
  48. 'last_name' => 'Doe'
  49. )
  50. );
  51. $firstNames = array_column($records, 'first_name');
  52. print_r($firstNames);
  53. /*
  54. Array
  55. (
  56. [0] => John
  57. [1] => Sally
  58. [2] => Jane
  59. [3] => Peter
  60. )
  61. */
  62. $records = array(
  63. array(1, 'John', 'Doe'),
  64. array(2, 'Sally', 'Smith'),
  65. array(3, 'Jane', 'Jones')
  66. );
  67. $lastNames = array_column($records, 2);
  68. print_r($lastNames);
  69. /*
  70. Array
  71. (
  72. [0] => Doe
  73. [1] => Smith
  74. [2] => Jones
  75. )
  76. */
  77. $mismatchedColumns = array(
  78. array(
  79. 'a' => 'foo',
  80. 'b' => 'bar',
  81. 'e' => 'baz'
  82. ),
  83. array(
  84. 'a' => 'qux',
  85. 'c' => 'quux',
  86. 'd' => 'corge'
  87. ),
  88. array(
  89. 'a' => 'grault',
  90. 'b' => 'garply',
  91. 'e' => 'waldo'
  92. ),
  93. );
  94. $foo = array_column($mismatchedColumns, 'a', 'b');
  95. print_r($foo);
  96. /*
  97. Array
  98. (
  99. [bar] => foo
  100. [0] => qux
  101. [garply] => grault
  102. )
  103. */
复制代码


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn