foreach()与list()的综合应用,用list给嵌套的数组解包
2016-09-07 17:35
609 查看
用 list() 给嵌套的数组解包
(PHP 5 >= 5.5.0, PHP 7)PHP 5.5 增添了遍历一个数组的数组的功能并且把嵌套的数组解包到循环变量中,只需将list() 作为值提供。
例如:
<?php $array = [ [1, 2], [3, 4], ]; foreach ($array as list($a, $b)) { // $a contains the first element of the nested array, // and $b contains the second element. echo "A: $a; B: $b\n"; } ?>
以上例程会输出:
A: 1; B: 2 A: 3; B: 4
list() 中的单元可以少于嵌套数组的,此时多出来的数组单元将被忽略:
<?php $array = [ [1, 2], [3, 4], ]; foreach ($array as list($a)) { // Note that there is no $b here. echo "$a\n"; } ?>
以上例程会输出:
1 3
如果 list() 中列出的单元多于嵌套数组则会发出一条消息级别的错误信息:
<?php $array = [ [1, 2], [3, 4], ]; foreach ($array as list($a, $b, $c)) { echo "A: $a; B: $b; C: $c\n"; } ?>
以上例程会输出:
Notice: Undefined offset: 2 in example.php on line 7 A: 1; B: 2; C: Notice: Undefined offset: 2 in example.php on line 7 A: 3; B: 4; C:
相关文章推荐
- List、Set、Map、数组遍历应用举例
- PHP 数组遍历方法大全(foreach,list,each)
- gridview和checkboxlist的嵌套相关应用
- php遍历数组 list foreach each方法总结
- php遍历数组 list foreach each方法总结
- 数组、List、ArrayList的使用以及for、foreach效率比较
- Python list嵌套 三维数组
- [转载]php-数组操作foreach、each、reset、list
- PHP 数组处理使用foreach、list、each等三个函数详解
- PHP 数组遍历方法大全(foreach,list,each)
- SIP与RTP综合应用5-RTP解包过程
- 两个list嵌套的foreach嵌套显示
- php数组的遍历讲解 for foreach list each key
- gridview和checkboxlist的嵌套相关应用
- list,linq综合应用
- [转载]php-数组操作foreach、each、reset、list
- PHP 数组遍历方法大全(foreach,list,each)
- List<Map>类型的JavaScript数组应用范例:图片多样化显示
- php遍历数组 list foreach each方法总结
- PHP:php遍历数组 foreach echo() list()总结