【发布时间】:2019-11-22 19:39:38
【问题描述】:
我有一个这样的数组:
$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_arrays 推入meta_query。如何正确地做到这一点?
【问题讨论】:
-
您显示为“我需要什么”的示例是不可能的。数组中不能有没有键值的元素。您将两个数组插入到一个数组中,但都没有一个键。下面的答案给了他们关键值 0 和 1。
-
当然@kainaw,你是对的。我更新了这个问题。我不知道为什么,在编写这样的代码时,您不必编写 [0] => 部分,但下面选择的答案对我、键和所有内容都有效。
标签: php arrays array-push