在 PHP 中,遍历一组非关联的多维数组,大部分代码是这样的:
$items = array(array('var1', 'var2', 'var3'),
array('var1', 'var2', 'var3'),
array('var1', 'var2', 'var3'),
array('var1', 'var2', 'var3'),
array('var1', 'var2', 'var3'),
);
foreach ($items as $item){list($var1, $var2, $var3) = $item;
if ($var1 == $var2){echo $var3;}
}
甚至在 foreach
外面没有用 list
:
foreach ($items as $item){$var1 = $item[0];
$var2 = $item[1];
$var3 = $item[3];
if ($var1 == $var2){echo $var3;}
}
其实当初能够在 foreach
外部利用 list
的赋值性能:
foreach ($items as list($var1, $var2, $var3)){if ($var1 == $var2){echo $var3;}
}
在 PHP 7.1 之后,也反对关联数组了:
$data = [["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
// list() style foreach ($data as list("id" => $id, "name" => $name)) {// logic here with $id and $name}
// [] style foreach ($data as ["id" => $id, "name" => $name]) {// logic here with $id and $name}
这样写的代码就简洁优雅多了!