PHP - 合并多个数组时的数组索引键

时间:2013-06-20 14:28:41

标签: php arrays wordpress merge key

我使用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循环动态添加分类法,这给了我这个数组:

分类关系args数组

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',
        );
    }

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

合并失败

这就是我的工作。添加我称之为$ tax_relations的数组。

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

到目前为止我的想法

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

2 个答案:

答案 0 :(得分:3)

你可以这样做:

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

答案 1 :(得分:0)

试试这个:

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