PHP – Array index key when merge multiple array

I use WordPress tax query and it looks like this:

Tax query

Read More
$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',
            )
        )
    );

Then I try to dynamically add taxonomies with a foreach loop which gives me this array:

Taxonomy relation args array

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 loop that creates array

Simplified.

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

When adding the array to the tax query args it does not work:

Merge fails

This is what I do. Add the array I call $tax_relations.

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

What I figured out so far

It’s because of the keys. It adds 0 => array instead of just array. How is this solved?

Related posts

Leave a Reply

2 comments

  1. You can do this like so:

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

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