-1

I have the following situation in my PHP script:

foreach( $recent_posts as $recent ) {
    /* something happens in here */
}

And:

foreach ($thumbnails as $thumbnail) {
   if ( has_post_thumbnail($thumbnail->ID)) {
      /* something other happens */
   }
}

I would like to combine these two foreach statements together. I've seen a few solutions around here, but nothing really works for me.

edit: i want to do something like this

echo '<a href="' . get_permalink( $thumbnail->ID ) . '" title="' . esc_attr( $thumbnail->post_title ) . '"> '. $recent["post_title"] . get_the_post_thumbnail($thumbnail->ID, 'thumbnail', array('class' => 'beitragimg')).' </a>';

4

3 回答 3

4

PHP 5.3.0开始,您可以为此使用MultipleIterator [PHP.net]类:

$a = new MultipleIterator();
$a->attachIterator(new ArrayIterator($recent_posts), 'recent');
$a->attachIterator(new ArrayIterator($thumbnails), 'thumbnail');

foreach ($a as $unit) {
    // $unit['recent'] 
    // $unit['thumbnail']
    if (has_post_thumbnail($unit['thumbnail']->ID)) {
        /* something other happens */ 
    }
}
于 2013-06-11T11:45:54.320 回答
0

您可以使用array_map

$a = ['red','yello','green'] ;
$b = ['apple','banna','mango'];

foreach(array_map(null, $a, $b) as $combined) {
    vprintf("%s %s\n", $combined);
}

输出

red apple
yello banna
green mango
于 2013-06-11T11:51:00.547 回答
-1

猜测您想要与此类似的东西,但根据变量的值,这有点猜测。

foreach( $recent_posts as $key => $recent ) {
    $thumbnail = $thumbnails[$key];

    if( has_post_thumbnail( $thumbnail->ID ) )
    {

    }
}
于 2013-06-11T11:45:12.150 回答