原文:https://www.cnblogs.com/JimmyBright/p/9869168.html
某些情况下,可以代替switch语句,大大简化代码,非常有意思哦
1 $list = [ 2 [ 3 'type'=>'a', 4 'name'=>'jimmy0', 5 'sex'=>'mail' 6 ], 7 [ 8 'type'=>'b', 9 'name'=>'jimmy1', 10 'sex'=>'femail' 11 ], 12 [ 13 'type'=>'c', 14 'name'=>'jimmy2', 15 'sex'=>'mail' 16 ], 17 [ 18 'type'=>'a', 19 'name'=>'jimmy3', 20 'sex'=>'femail' 21 ], 22 [ 23 'type'=>'b', 24 'name'=>'jimmy4', 25 'sex'=>'femail' 26 ], 27 [ 28 'type'=>'a', 29 'name'=>'jimmy5', 30 'sex'=>'femail' 31 ] 32 ]; 33 $aList = []; 34 $bList = []; 35 $cList = []; 36 foreach ($list as $item) { 37 $v = $item['type'].'List'; 38 $$v = array_merge($$v,[$item]);//一般的做法就是在这里用switch语句了,这边就不需要了,一行代码搞定 39 } 40 var_export($aList); 41 echo PHP_EOL;echo PHP_EOL; 42 var_export($bList); 43 echo PHP_EOL;echo PHP_EOL; 44 var_export($cList); 45 echo PHP_EOL;echo PHP_EOL; 46 exit;
看一下输出:
1 array ( 2 0 => 3 array ( 4 'type' => 'a', 5 'name' => 'jimmy0', 6 'sex' => 'mail', 7 ), 8 1 => 9 array ( 10 'type' => 'a', 11 'name' => 'jimmy3', 12 'sex' => 'femail', 13 ), 14 2 => 15 array ( 16 'type' => 'a', 17 'name' => 'jimmy5', 18 'sex' => 'femail', 19 ), 20 ) 21 22 array ( 23 0 => 24 array ( 25 'type' => 'b', 26 'name' => 'jimmy1', 27 'sex' => 'femail', 28 ), 29 1 => 30 array ( 31 'type' => 'b', 32 'name' => 'jimmy4', 33 'sex' => 'femail', 34 ), 35 ) 36 37 array ( 38 0 => 39 array ( 40 'type' => 'c', 41 'name' => 'jimmy2', 42 'sex' => 'mail', 43 ), 44 ) 45 46 47 Process finished with exit code 0