您的位置:首页 > 其它

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:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: