PHP:迭代两个并行数组的最佳方法? [英] PHP: Best way to iterate two parallel arrays?
问题描述
正如在另一个答案中所见,有几种方法可以同时迭代两个相同大小的数组;但是,所有这些方法都存在相当严重的缺陷。以下是一些建议方法的注意事项:
As seen in this other answer, there are several ways to iterate two same-sized arrays simultaneously; however, all of the methods have a rather significant pitfall. Here are some of the caveats with the methods suggested:
- 您不能使用
FALSE
其中一个数组中的值。 - 您只能在其中一个数组中使用标量值。
- 您必须使用数字索引数组。
- 两个阵列必须共享相同的密钥。
- 等等。
- You can't use
FALSE
values in one of the arrays. - You can only use scalar values in one of the arrays.
- You must use numerically indexed arrays.
- Both arrays must share the same keys.
- Etc.
我的问题是 - 是否有一种方法可以做到这一点,不会受到任何这些(或其他)重要警告的影响?
请记住,我只是出于好奇而问这个问题;我没有考虑用例,甚至不知道这种情况是否确实存在,或者在现实世界中是否有用/实用。但是,这里有一些示例数据:
Bear in mind that I'm simply asking this out of curiosity; I have no use-case in mind, nor do I even know if such a case actually exists or would be useful/practical in a real-world scenario. However, here is some example data:
$arr1 = [ 'a' => 1, 'b' => FALSE, 'c' => new DateTime() ];
$arr2 = [ 'foo', TRUE, 7 ];
推荐答案
您可以使用 MultipleIterator
:
You can use a MultipleIterator
:
$iterator = new MultipleIterator;
$iterator->attachIterator(new ArrayIterator($array1));
$iterator->attachIterator(new ArrayIterator($array2));
foreach ($iterator as $values) {
var_dump($values[0], $values[1]);
}
您可以找到更多关于各种选项的示例在文档中。
You can find more examples concerning the various options in the docs.
这篇关于PHP:迭代两个并行数组的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!