Combining vertical and horizontal lines, an upgraded version of the record set super processing function array_column is implemented

WBOY
Release: 2016-07-25 08:48:35
Original
999 people have browsed it
Highlights: Simplified operations, array_walk batch processing, references, and low internal consumption.

Application scenarios: Mainly used to process record sets (two-dimensional arrays)
1. Integrate result sets (one-dimensional arrays, such as ids: [1,3,4,5], list of winning user names: ['Xiong Ming' ,'lijia','Erlangshen'])
2. Combined key-value pair (one-dimensional array, such as tag: array('mysql'=>'url1','php'=>'url2'])
3. Cache File data (id=>info)

Note: PHP5.5 version is a built-in function, please pay attention to naming conflicts before use

From (EQPHP tool class): https://github.com/eqphp/framework/ blob/master/www/class/fun.php

Demo works: http://www.eqphp.com/blog/list/
  1. //Processing record sets (built-in in php5.5)
  2. static function array_column($data,$key='id',$column=null){
  3. $buffer=null;
  4. if ($column) {
  5. //k=>v
  6. if (strpos($column,',') === false) {
  7. foreach ($data as $value) {
  8. $buffer[$value[$key]]=$ value[$column];
  9. }
  10. return $buffer;
  11. }
  12. //k=arr
  13. $field=explode(',',$column);
  14. foreach ($data as $value) {
  15. $id= $value[$key];
  16. array_walk($value,function ($v,$k) use (&$value,$field){
  17. if (!in_array($k,$field)) unset($value[$ k]);
  18. });
  19. $buffer[$id]=$value;
  20. }
  21. return $buffer;
  22. }
  23. //id_arr
  24. foreach ($data as $value) {
  25. $buffer[]=$ value[$key];
  26. }
  27. return $buffer;
  28. }
  29. //Usage demo:
  30. //Original record set:
  31. $data=array(
  32. array('id'=>1,'name '=>'dubox','age'=>25,'girlfriend'=>'Soda Green'),
  33. array('id'=>4,'name'=>'Xiao Chunzi',' age'=>21,'girlfriend'=>'don't know'),
  34. array('id'=>9,'name'=>'idiot','age'=>71,'girlfriend '=>'widow'),
  35. );
  36. $ids=array_column($data,'id');
  37. //out: array(1,4,9);
  38. $info=array_column($data ,'name','girlfriend');
  39. //out: array('dubox'=>'Soda Green','Xiao Chunzi'=>'I don't know','idiot'=>'Widow');
  40. $cache=array_column($data,'id','name,age,girlfriend');
  41. //out: array(
  42. 1=>array('name'=>'dubox','age' =>25,'girlfriend'=>'Soda Green'),
  43. 4=>array('name'=>'Xiao Chunzi','age'=>21,'girlfriend'=>'No know'),
  44. 9=>array('name'=>'idiot','age'=>71,'girlfriend'=>'widow'),
  45. );
Copy code


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template