批改状态:合格
老师批语:
(1)快速遍历foreach
$user3 = ['id'=>1,'name'=>'Jack','age'=>28,'address'=>'深圳龙华'];foreach($user3 as $key=>$value){printf('[%s]=>%s<hr>',$key,$value);}

(2) 结构遍历foreach
// 解构遍历通常用来遍历二维或者以上的数组$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)数组查询 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)数组删除 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)数组更新
// 更新:第2个位置删除2个,使用新的数据来替换掉它$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)数组添加
// 添加: 第2个位置删除0个,传入的新数据会追加到当前位置的后面$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: 仅返回数组中可转为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');

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号