【问题标题】:PHP - Array index key when merge multiple arrayPHP - 合并多个数组时的数组索引键
【发布时间】:2013-06-17 11:13:45
【问题描述】:

我使用 WordPress 税务查询,它看起来像这样:

税务查询

$args = array(
        'post_type' => 'post',
        'post__not_in' => array($post->ID),
        'tax_query' => array(
            'relation' => 'OR',
            array(
                'taxonomy' => 'color',
                'terms' => $color_array,
                'field' => 'slug',
            ),
            array(
                'taxonomy' => 'brand',
                'terms' => $brand_array,
                'field' => 'slug',
            )
        )
    );

然后我尝试使用 foreach 循环动态添加分类法,这给了我这个数组:

分类关系参数数组

array (size=2)
  0 => 
    array (size=3)
      'taxonomy' => string 'color' (length=5)
      'terms' => 
        array (size=1)
          0 => string 'pink' (length=4)
      'field' => string 'slug' (length=4)
  1 => 
    array (size=3)
      'taxonomy' => string 'brand' (length=11)
      'terms' => 
        array (size=2)
          0 => string 'star' (length=15)
          1 => string 'testar' (length=6)
      'field' => string 'slug' (length=4)

创建数组的foreach循环

简化。

$tax_relations = array();
    foreach( $taxes as $tax ) {
        $tax_relations[] = array(
            'taxonomy' => $tax,
            'terms' => $tax_array,
            'field' => 'slug',
        );
    }

将数组添加到税收查询参数时,它不起作用:

合并失败

这就是我所做的。添加我称为 $tax_relations 的数组。

$args = array(
    'post_type' => 'post',
    'post__not_in' => array($post->ID),
    'tax_query' => array(
        'relation' => 'OR', $tax_relations
    )
);

到目前为止我发现了什么

这是因为钥匙。它添加了 0 => 数组,而不仅仅是数组。这是怎么解决的?

【问题讨论】:

    标签: php arrays wordpress merge key


    【解决方案1】:

    你可以这样做:

    $args = array(
        'post_type' => 'post',
        'post__not_in' => array($post->ID),
        'tax_query' => array_merge(array('relation' => 'OR'), $tax_relations)
    );
    

    【讨论】:

      【解决方案2】:

      试试这个:

      $args = array(
          'post_type' => 'post',
          'post__not_in' => array($post->ID),
          'tax_query' => array(
              'relation' => 'OR',
          ) + $tax_relations
      );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-11-11
        • 2018-09-02
        • 2013-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多