Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

loops - 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:

  • 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.

My question is - is there a method for doing this which doesn't suffer from any of these (or other) significant caveats?

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 ];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...