我有一个像这样的数组:
$args = array(
'post_type' => 'player',
'posts_per_page' => -1,
);
然后我有了另一个数组,例如:
[stateArray] => Array
(
[0] => OR
[1] => WI
)
我需要添加到原始$args
数组中以具体获得此结果:
$args = array(
'post_type' => 'player',
'posts_per_page' => -1,
'meta_query' => array(
'compare' => 'AND',
[0] => array(
'key' => 'state',
'value' => 'OR',
'compare' => '=',
),
[1] => array(
'key' => 'state',
'value' => 'WI',
'compare' => '=',
),
)
);
尝试此代码:
$stateArray = $_POST['stateArray'];
$state_array_wrapper = array('meta_query' => array());
foreach ($stateArray as $state) {
$single_state_array = array(
'key' => 'town_state',
'value' => $state,
'compare' => '='
);
array_push($state_array_wrapper, $single_state_array);
}
$state_array_wrapper = array_values($state_array_wrapper);
array_push($args, $state_array_wrapper);
我得到这个结果:
Array (
[post_type] => player
[posts_per_page] => -1
[0] => Array
(
[0] => Array
(
)
[1] => Array
(
[key] => town_state
[value] => OR
[compare] => =
)
[2] => Array
(
[key] => town_state
[value] => WI
[compare] => =
)
)
)
不确定为什么我在最终数组中根本看不到'meta_query'
,或者不确定如何将这两个$single_state_array
推送到meta_query中,即使我确实看到了它。如何正确地做到这一点?
答案 0 :(得分:1)
您需要为$ args提供meta_query的密钥 那么您需要推送到该数组
$args['meta_query'] = array('compare'=>'AND');
foreach ($stateArray as $state) {
$single_state_array = array(
'key' => 'town_state',
'value' => $state,
'compare' => '='
);
array_push($args['meta_query'], $single_state_array);
/* short hand in php 7 */
//$args['meta_query'][] = $single_state_array;
}
答案 1 :(得分:0)
这看起来很简单。请告诉我我是否看错了...
$args['meta_query'] = array('compare'=>'AND');
foreach($stateArray as $val)
$args['meta_query'][] = array('key'=>'town_state', 'value'=>$val, 'compare'=>'=');
仅此而已。