开发者

AND in a PHP foreach loop?

Is it possible to have an AND in a foreach loop?

For Example,

foreach ($bookmarks_latest as $book开发者_开发技巧mark AND $tags_latest as $tags)


You can always use a loop counter to access the same index in the second array as you are accessing in the foreach loop (i hope that makes sense).

For example:-

$i = 0;
foreach($bookmarks_latest as $bookmark){
   $result['bookmark'] = $bookmark;
   $result['tag'] = $tags_latest[$i];
   $i++;
}

That should achieve what you are trying to do, otherwise use the approach sugested by dark_charlie.

In PHP 5 >= 5.3 you can use MultipleIterator.


Short answer: no. You can always put the bookmarks and tags into one array and iterate over it.

Or you could also do this:

reset($bookmarks_latest);
reset($tags_latest);
while ((list(, $bookmark) = each($bookmarks_latest)) && (list(,$tag) = each($tags_latest)) {
    // Your code here that uses $bookmark and $tag
}

EDIT:
The requested example for the one-array solution:

class BookmarkWithTag  {
  public var $bookmark;
  public var $tag;
}

// Use the class, fill instances to the array $tagsAndBookmarks


foreach ($tagsAndBookmarks as $bookmarkWithTag)  {
  $tag = $bookmarkWithTag->tag;
  $bookmark = $bookmarkWithTag->bookmark;
}


you can't do that.

but you can

<?php
foreach($keyval as $key => $val) {
  // something with $key and $val
}

the above example works really well if you have a hash type array but if you have nested values in the array I recommend you:

or option 2

<?php
foreach ($keyval as $kv) {
 list($val1, $val2, $valn) = $kv;
}


No, but there are many ways to do this, e.g:

reset($tags_latest);
foreach ($bookmarks_latest as $bookmark){
    $tags = current($tags_latest); next($tags_latest);
    // here you can use $bookmark and $tags
}


No. No, it is not.

You'll have to manually write out a loop that uses indexes or internal pointers to traverse both arrays at the same time.


Yes, for completeness:

foreach (array_combine($bookmarks_latest, $tags_latest) as $bookm=>$tag)

That would be the native way to get what you want. But it only works if both input arrays have the exact same length, obviously.

(Using a separate iteration key is the more common approach however.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜