
批改狀態(tài):合格
老師批語:
(1)快速遍歷foreach
$user3 = ['id'=>1,'name'=>'Jack','age'=>28,'address'=>'深圳龍華'];
foreach($user3 as $key=>$value){
printf('[%s]=>%s<hr>',$key,$value);
}
(2) 結(jié)構(gòu)遍歷foreach
// 解構(gòu)遍歷通常用來遍歷二維或者以上的數(shù)組
$user4 = [
['id'=>1,'name'=>'小明'],
['id'=>2,'name'=>'張三'],
['id'=>3,'name'=>'李四'],
];
foreach($user4 as list('id'=>$id,'name'=>$name)){
printf('$id=%s,$name=%s<hr>',$id,$name);
}
(1)相加 array_sum
// 相加
function sum(...$args)
{
return array_sum($args);
}
echo sum(1,2,3,4,5,6,7).'<hr>';
(2)相乘 array_product
// 相乘
function mul(...$args)
{
return array_product($args);
}
echo '相乘積為:'.mul(2,3,4,5).'<hr>';
(1)數(shù)組查詢 array_slice
$user = ['id'=>1,'name'=>'張三','age'=>18,'course'=>'php','grade'=>90];
printf('<pre>%s<hr></pre>',print_r($user,true));
// array_slice
// 前兩個
$res = array_slice($user,0,2);
printf('<pre>%s<hr></pre>',print_r($res,true));
// 后兩個
$res2 = array_slice($user,-2,2);
// $res2 = array_slice($user,-2,1);
printf('<pre>%s<hr></pre>',print_r($res2,true));
(2)數(shù)組刪除 array_splice
// array_splice
$arr = [1,2,3,4,5,6,7,8,9,10];
printf('<pre>%s<hr></pre>',print_r($arr,true));
// 刪除:第2個位置刪除2個
$res3 = array_splice($arr,1,2);
printf('<pre>%s<hr></pre>',print_r($res3,true));
printf('<pre>%s<hr></pre>',print_r($arr,true));
(3)數(shù)組更新
// 更新:第2個位置刪除2個,使用新的數(shù)據(jù)來替換掉它
$res4 = array_splice($arr,1,2,['A','B']);
printf('<pre>%s<hr></pre>',print_r($res4,true));
printf('<pre>%s<hr></pre>',print_r($arr,true));
(4)數(shù)組添加
// 添加: 第2個位置刪除0個,傳入的新數(shù)據(jù)會追加到當前位置的后面
$res5 = array_splice($arr,1,0,['hello','world']);
printf('<pre>%s<hr></pre>',print_r($res5,true));
printf('<pre>%s<hr></pre>',print_r($arr,true));
(1)過濾器 array_filter
// array_filter: 僅返回數(shù)組中可轉(zhuǎn)為true的元素集合
$arr = [
150,
'php',
true,
[4, 5, 6],
(new class
{
}),
[],
null,
false,
'',
0,
'0'
];
$res = array_filter($arr,function($item){
if($item){
// 檢測變量是否是一個標量描述
return is_scalar($item);
}
});
printf('<pre>%s<hr></pre>',print_r($res,true));
(2)過濾器 array_map
// array_map
$arr2 = ['php', [3, 4, 5], (new class
{
public $name = '電腦';
public $price = 8888;
}), 15, 20];
printf('<pre>%s<hr></pre>',print_r($arr2,true));
$res2 = array_map(function($item){
switch(gettype($item)){
case 'array':
$item = join(',',$item);
break;
case 'object':
$item = join(',',get_object_vars($item));
}
return $item;
},$arr2);
printf('<pre>%s<hr></pre>',print_r($res2,true));
(3)歸并 array_reduce
// 3.歸并
$arr3 = [10,20,30,40,50];
$res3 = array_reduce($arr3,function($acc,$cur){
echo $acc, ', ', $cur, '<br>';
return $acc + $cur;
},0);
echo $res3.'<hr>';
(4)array_walk
// 4.array_walk
$user = ['id' => 10, 'name' => 'admin', 'email' => 'admin@php.cn'];
array_walk($user,function($value,$key,$color){
printf('[%s]=><span style="color:%s">%s</span>', $key, $color, $value);
},'orange');
微信掃碼
關(guān)注PHP中文網(wǎng)服務號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號