Stender
Stender

Reputation: 2492

Array into Comma separated array in PHP.

So, I am building a wordpress query containing a meta query.

I am getting some meta values, from some different earlier functions, which seems to work fine.

ending up with : $arrayOfVendors = array(92,85,72).

I am then trying to create a dynamic meta query, with a foreach loop.

This is done by looping through my array, and creating new arrays by the values.

$test2QueryStringArray = array();
    foreach ($arrayOfVendors as $singleVendorObject) {

        $test2QueryString = array(
        'key' => 'products_vendor',
        'compare'   => 'LIKE',
        'value'=> '"'.$singleVendorObject.'"',
        );

        array_push($test2QueryStringArray, $test2QueryString);
    }

Now my new array, should consist of several arrays containing what I desire.

And by just putting it into my args, I should have everything I want

'meta_query'             => array(
        'relation' => 'OR',

            $test2QueryStringArray
        )

BUT - What I end up with is the following.

'meta_query' =>   array (    
    'relation' => 'OR',    
     0 => array (
         0 => array (
            'key' => 'products_vendor',
            'compare' => 'LIKE',
            'value' => '92',
        ),
        1 => array (
            'key' => 'products_vendor',
            'compare' => 'LIKE',
            'value' => '85',
        ),
        2 => array (
            'key' => 'products_vendor',
            'compare' => 'LIKE',
            'value' => '72',
        ),
    ),
)

While the correct syntax would be the following here.

'meta_query' => array(
    'relation' => 'OR',
     array(
        'key'     => 'products_vendor',
        'compare' => 'LIKE',
        'value'   => '92',
    ),
    array(
        'key'     => 'products_vendor',
        'compare' => 'LIKE',
        'value'   => '85',
    ),
    array(
        'key'     => 'products_vendor',
        'compare' => 'LIKE',
        'value'   => '72',
    ),
),

Basically, What I am trying to do, is to get all posts, that has selected the vendor from the array, in an ACF relationship field (where it is possible to select multiple vendors.)

Not sure how to proceed from here, everything I have tried, either dies because of array to string conversion, or simply does not give me my expected output.

So any help will be appreciated <3

Upvotes: 1

Views: 216

Answers (1)

Nick
Nick

Reputation: 147146

With this line:

'meta_query' => array('relation' => 'OR',
                      $test2QueryStringArray
                      )

you are pushing $test2QueryStringArray into the meta_query array. Hence the extra level of nesting you get. What you want to do is a merge:

'meta_query' => array_merge(array('relation' => 'OR'),
                            $test2QueryStringArray
                           )

Upvotes: 3

Related Questions