douzhang5984 2016-07-29 07:18
浏览 23
已采纳

php foreach中的上下文如何工作?

I'm writing a simple tab navigation and I'm facing this issue:

The function print_office works only when I'm inside a foreach.

//Doesn't work
print_office($loop->posts[0], true);

//Works
foreach ($loop->posts as $index => $post) {
    print_office($post, true);
}

The print_office function makes use of Advanced Custom Fields' get_field('field_name').

EDIT:

I've put a var_dump($office) inside print_office.

When called outside the foreach I get:

object(WP_Post)#317 (24) {
  ["ID"]=> int(7)
  ["post_author"]=> string(1) "1"

  [.....] //More fields;
}

When called inside the foreachI get:

FOREACH:object(WP_Post)#317 (24) {
  ["ID"]=> int(7)
  ["post_author"]=> string(1) "1"

  [.....] //More fields;
}

So the only difference is that: FOREACH:object instead of just object.

  • 写回答

2条回答 默认 最新

  • douchensou6969 2016-07-29 07:40
    关注

    The problem is just that, when it does not work, there's no $post variable, and the get_field('field_name') returns the field for the current post, which is really $post

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?