$arr=['a1'=>['b1'=>['c1'=>['d1','d2','d3'],'c2'=>['d1','d2','d3'],],'b2'=>['c1'=>['d1','d2','d3'],'c2'=>['d1','d2','d3'],]],'a2'=>['b1'=>['c1'=>['d1','d2','d3'],'c2'=>['d1','d2','d3'],],'b2'=>['c1'=>['d1','d2','d3'],'c2'=>['d1','d2','d3'],]],];有上面一个数组,现在想通过三个参数($a,$b,$c),来动态的取数组中值。情况如下:1、如果三个参数全为空,返回$arr;2、如果$a不为空,返回$arr[$a];3、如果$a、$b不为空,返回$arr[$a][$b];4、如果$a、$b、$c不为空,返回$arr[$a][$b][$c];函数的形参可以是三个参数,或者是数组,或者动态获取传入的参数。我写了两个函数,总感觉不太简单,特来请教。//函数1functionthe_array($a='',$b='',$c=''){$arr=['上面那个数组'];$brr=array_filter([$a,$b,$c]);switch(count($brr)){case1:return$arr[$a]??[];break;case2:return$arr[$a][$b]??[];break;case3:return$arr[$a][$b][$c]??[];break;default:return$arr;break;}}//函数2functionthe_array(...$param){$arr=['上面那个数组'];$brr=array_filter($param);//或者用func_get_args()获取传入的参数switch(count($brr)){case1:$a=$param;return$arr[$a]??[];break;case2:[$a,$b]=$param;return$arr[$a][$b]??[];break;case3:[$a,$b,$c]=$param;return$arr[$a][$b][$c]??[];break;default:return$arr;break;}}
2 回答
慕村225694
TA贡献1880条经验 获得超4个赞
$arr=['a1'=>['b1'=>['c1'=>['d1','d2','d3'],'c2'=>['d1','d2','d3'],],'b2'=>['c1'=>['d1','d2','d3'],'c2'=>['d1','d2','d3'],]],'a2'=>['b1'=>['c1'=>['d1','d2','d3'],'c2'=>['d1','d2','d3'],],'b2'=>['c1'=>['d1','d2','d3'],'c2'=>['d1','d2','d3'],]],];functionarray_get($arr,...$flag){if(empty($flag)){return$arr;}foreach($flagas$item){if(!isset($arr[$item])){//TODOReturn$arrornullreturnnull;}$arr=$arr[$item];}return$arr;}$result=array_get($arr,'a1','b1','c1');var_dump($result);建议学习Laravel的Arr::get()framework/Arr.phpat5.4·laravel/framework
添加回答
举报
0/150
提交
取消