当需要从多维数组中获取值,并且进行判空,赋值默认值的时候
可以使用下面的测试用例
$arr=[ "name"=>"陶士涵", "title"=>[ "sub"=>"测试" ], "test"=>null, "desc"=>"", "num"=>0, ]; $name=data_get($arr,"name","a"); $subTitle=data_get($arr,"title.sub","a"); $mainTitle=data_get($arr,"title.main","a");//如果没有这个key的情况下,默认值起作用,返回string(1) "a" $test=data_get($arr,"test","a");//如果是null的情况下,默认值不起作用,返回null $test2=data_get($arr,"test","a") ?? "a";//如果是null的情况下,??可以起作用,返回string(1) "a" $desc=data_get($arr,"desc","a") ?: "a";//如果是""的情况下,?:可以起作用,返回string(1) "a" $num=data_get($arr,"num","a") ?: 100;//如果是0的情况下,?:可以起作用,返回int(100) var_dump($name,$subTitle,$mainTitle,$test,$test2,$desc,$num);
可以总结出,最兼容的写法是
data_get 与 ?:进行配合 ,类似下面这样
$desc=data_get($arr,"desc","a") ?: "a";