【问题标题】:Adding arrays into an array, and associate it with a specific key将数组添加到数组中,并将其与特定键关联
【发布时间】: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


【解决方案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;
}

【讨论】:

  • 完美,就像一个魅力!感谢您对 php 7 速记的说明!
  • 这也适用于php,希望您使用php 7,php 5需要将数组创建为“array()”,php 7您可以使用“$arr = [];”祝你好运
【解决方案2】:

这看起来很简单。如果我看错了,请告诉我...

$args['meta_query'] = array('compare'=>'AND');
foreach($stateArray as $val)
  $args['meta_query'][] = array('key'=>'town_state', 'value'=>$val, 'compare'=>'=');

就是这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多