原文:https://www.cnblogs.com/JimmyBright/p/9869168.html
某些情况下,可以代替switch语句,大大简化代码,非常有意思哦
$list = [
[
'type'=>'a',
'name'=>'jimmy0',
'sex'=>'mail'
],
[
'type'=>'b',
'name'=>'jimmy1',
'sex'=>'femail'
],
[
'type'=>'c',
'name'=>'jimmy2',
'sex'=>'mail'
],
[
'type'=>'a',
'name'=>'jimmy3',
'sex'=>'femail'
],
[
'type'=>'b',
'name'=>'jimmy4',
'sex'=>'femail'
],
[
'type'=>'a',
'name'=>'jimmy5',
'sex'=>'femail'
]
];
$aList = [];
$bList = [];
$cList = [];
foreach ($list as $item) {
$v = $item['type'].'List';
$$v = array_merge($$v,[$item]);//一般的做法就是在这里用switch语句了,这边就不需要了,一行代码搞定
}
var_export($aList);
echo PHP_EOL;echo PHP_EOL;
var_export($bList);
echo PHP_EOL;echo PHP_EOL;
var_export($cList);
echo PHP_EOL;echo PHP_EOL;
exit;
看一下输出:
array (
0 =>
array (
'type' => 'a',
'name' => 'jimmy0',
'sex' => 'mail',
),
1 =>
array (
'type' => 'a',
'name' => 'jimmy3',
'sex' => 'femail',
),
2 =>
array (
'type' => 'a',
'name' => 'jimmy5',
'sex' => 'femail',
),
) array (
0 =>
array (
'type' => 'b',
'name' => 'jimmy1',
'sex' => 'femail',
),
1 =>
array (
'type' => 'b',
'name' => 'jimmy4',
'sex' => 'femail',
),
) array (
0 =>
array (
'type' => 'c',
'name' => 'jimmy2',
'sex' => 'mail',
),
) Process finished with exit code 0
输出