In development, it is often necessary to process the list data taken from the database,
See the following three kinds of writing, you can get the same results, the individual has been accustomed to use the first kind.
What's better to consider in terms of readability and performance?
List data such as:
$list = [ [ 'uid'=>100, 'username'=>'test100', 'nickname'=>'php_1', 'gender'=>1, ], [ 'uid'=>200, 'username'=>'test200', 'nickname'=>'php_2', 'gender'=>2, ], [ 'uid'=>300, 'username'=>'test300', 'nickname'=>'php_3', 'gender'=>0, ],];
Notation 1, modify the original array:
foreach($list as $k=>$v){ if($v['gender']==0){ $list[$k]['gender']='妖人'; }else{ $list[$k]['gender']='人'; }}
Notation 2, the original array modified, using the reference:
foreach($list as &$v){ if($v['gender']==0){ $v['gender']='妖人'; }else{ $v['gender']='人'; }}
Notation 3, define a new array:
$data = [];foreach($list as $k=>$v){ if($v['gender']==0){ $v['gender']='妖人'; }else{ $v['gender']='人'; } $data[] = $v;}
Reply content:
In development, it is often necessary to process the list data taken from the database,
See the following three kinds of writing, you can get the same results, the individual has been accustomed to use the first kind.
What's better to consider in terms of readability and performance?
List data such as:
$list = [ [ 'uid'=>100, 'username'=>'test100', 'nickname'=>'php_1', 'gender'=>1, ], [ 'uid'=>200, 'username'=>'test200', 'nickname'=>'php_2', 'gender'=>2, ], [ 'uid'=>300, 'username'=>'test300', 'nickname'=>'php_3', 'gender'=>0, ],];
Notation 1, modify the original array:
foreach($list as $k=>$v){ if($v['gender']==0){ $list[$k]['gender']='妖人'; }else{ $list[$k]['gender']='人'; }}
Notation 2, the original array modified, using the reference:
foreach($list as &$v){ if($v['gender']==0){ $v['gender']='妖人'; }else{ $v['gender']='人'; }}
Notation 3, define a new array:
$data = [];foreach($list as $k=>$v){ if($v['gender']==0){ $v['gender']='妖人'; }else{ $v['gender']='人'; } $data[] = $v;}
Use 1 more
Although the 2 is the most concise, but the foreach reference is a pit
If you use the $V variable again outside of foreach, you may change the last value of the foreach, and you can guarantee that it won't happen without it.
Array_map
The individual generally uses the wording one
Two easy problems
Recommended way to refer to, that is, the wording 2
The second kind of better, you are all foreach out, there is a one-dimensional array exists, why do you want to go to the list to take it.
Select if (gender=0, ' Demon Man ', ' person ') as gendername ...
Get used to the first way