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/
- //Processing record sets (built-in in php5.5)
- static function array_column($data,$key='id',$column=null){
-
- $buffer=null;
-
- if ($column) {
- //k=>v
- if (strpos($column,',') === false) {
- foreach ($data as $value) {
- $buffer[$value[$key]]=$ value[$column];
- }
- return $buffer;
- }
-
- //k=arr
- $field=explode(',',$column);
- foreach ($data as $value) {
- $id= $value[$key];
- array_walk($value,function ($v,$k) use (&$value,$field){
- if (!in_array($k,$field)) unset($value[$ k]);
- });
- $buffer[$id]=$value;
- }
- return $buffer;
- }
-
- //id_arr
- foreach ($data as $value) {
- $buffer[]=$ value[$key];
- }
- return $buffer;
- }
-
-
-
- //Usage demo:
- //Original record set:
- $data=array(
- array('id'=>1,'name '=>'dubox','age'=>25,'girlfriend'=>'Soda Green'),
- array('id'=>4,'name'=>'Xiao Chunzi',' age'=>21,'girlfriend'=>'don't know'),
- array('id'=>9,'name'=>'idiot','age'=>71,'girlfriend '=>'widow'),
- );
-
- $ids=array_column($data,'id');
- //out: array(1,4,9);
-
- $info=array_column($data ,'name','girlfriend');
- //out: array('dubox'=>'Soda Green','Xiao Chunzi'=>'I don't know','idiot'=>'Widow');
-
- $cache=array_column($data,'id','name,age,girlfriend');
- //out: array(
- 1=>array('name'=>'dubox','age' =>25,'girlfriend'=>'Soda Green'),
- 4=>array('name'=>'Xiao Chunzi','age'=>21,'girlfriend'=>'No know'),
- 9=>array('name'=>'idiot','age'=>71,'girlfriend'=>'widow'),
- );
Copy code
|