【发布时间】:2017-12-06 21:05:47
【问题描述】:
有没有办法将数组作为变量从 wp_query 循环中传递出去?我想从四个帖子中收集帖子元数据——下周和接下来的三周。为了保持代码干净,我认为捕获变量并稍后在表单中使用数据是最简单的。
// Capture next week's week number
$nextweek = date("W", strtotime( "+1 week"));
// Query all custom post types
$menu_args = array(
'post_type'=>'single_menu',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC'
);
$menu = new WP_Query( $menu_args ); if ( $menu->have_posts() ) : while ( $menu->have_posts() ) : $menu->the_post();
// Get custom fields
$menuids = array( get_post_field( 'week', $post->id ) );
$titles = array( get_post( $post->id )->post_title );
$choosefrom = array( get_post_field( 'menu_listing', $post->id ) );
$selection = array( get_post_field( $checkout_menu, $post->id ) );
// Create new array with custom fields
$result = array();
foreach ( $menuids as $id => $menuid ) {
$result[$menuid] = array(
'title' => $titles[$id],
'offering' => $choosefrom[$id],
'menu' => $selection[$id],
'delivery' => 0,
);
}
// Return the arrays for specified weeks
for ($i = $nextweek; $i<$nextweek+4; $i++) {
if ( $result[$menuid] == $result[$i] ) {
print_r( $result );
}
}
endwhile;
endif;
print_r() 返回正确的结果,我的$results 数组接下来的四个星期。但是,当我创建一个变量并在循环外调用它时,如下所示,我只得到数组中的最后一个/第四个$result:
for ($i = $nextweek; $i<$nextweek+4; $i++) {
if ( $result[$menuid] == $result[$i] ) {
$payload = $result;
}
}
endwhile;
endif;
print_r( $payload );
当我像这样创建一个新数组时也会发生同样的事情:
$payload = array();
for ($i = $nextweek; $i<$nextweek+4; $i++) {
if ( $result[$menuid] == $result[$i] ) {
$payload[] = $result;
}
}
endwhile;
endif;
print_r( $payload );
如果我像$payload .= $result; 这样连接变量,我会返回ArrayArrayArrayArray。
我知道我可以在循环内回显表单,但如果可能的话,我宁愿将数组作为数据变量。我错过了一些简单的东西吗?
【问题讨论】:
-
您只是在寻找
$posts属性...? codex.wordpress.org/Class_Reference/… -
我在传递我在
endwhile和endif循环之外创建的数据数组时遇到问题。$posts属性如何帮助我实现这一目标? -
不太确定你的问题是什么......它可能只是如何在循环中添加新元素到数组中,而不是覆盖 i> 每次迭代中的变量...?如果是这样,这对研究来说是相当微不足道的,google.com/…
-
好吧,感谢您指出这应该很容易。原来我的问题是我需要将
payload = array();放在循环之外。你帮助我停止了过度思考。
标签: php arrays wordpress loops