Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - multidimensional array to query string

Searched for so long but didn't get any feasible answer.


A) Input:

$array = array(
            'order_source' => array('google','facebook'), 
            'order_medium' => 'google-text'
          );


Which looks like:

Array
(
    [order_source] => Array
        (
            [0] => google
            [1] => facebook
        )

    [order_medium] => google-text
)


B) Required output:

order_source=google&order_source=facebook&order_medium=google-text


C) What I've tried (http://3v4l.org/b3OYo):

$arr = array('order_source' => array('google','facebook'), 'order_medium' => 'google-text');

function bqs($array, $qs='')
{
    foreach($array as $par => $val)
    {
        if(is_array($val))
        {
            bqs($val, $qs);       
        }
        else
        {
           $qs .= $par.'='.$val.'&';
        }
    }
    return $qs;
}

echo $qss = bqs($arr);


D) What I'm getting:

order_medium=google-text&


Note: It should also work for any single dimensional array like http_build_query() works.

like image 374
Parag Tyagi Avatar asked Jun 09 '26 08:06

Parag Tyagi


2 Answers

I hope that this is what you are looking for, it works with single to n-dimensinal arrays.

$walk = function( $item, $key, $parent_key = '' ) use ( &$output, &$walk ) {

    is_array( $item ) 
        ? array_walk( $item, $walk, $key ) 
        : $output[] = http_build_query( array( $parent_key ?: $key => $item ) );

};

array_walk( $array, $walk );

echo implode( '&', $output );  // order_source=google&order_source=facebook&order_medium=google-text 
like image 192
Danijel Avatar answered Jun 11 '26 22:06

Danijel


You don't really need to do anything special here.

$array = array(
    'order_source' => array('google', 'facebook'),
    'order_medium' => 'google-text'
);
$qss = http_build_query($array);

On the other side:

var_dump($_GET);

Result:

array(2) {
  ["order_source"]=>
  array(2) {
    [0]=>
    string(6) "google"
    [1]=>
    string(8) "facebook"
  }
  ["order_medium"]=>
  string(11) "google-text"
}

This really is the best way to send arrays as GET variables.

If you absolutely must have the output as you've defined, this will do it:

function bqs($array, $qs = false) {
    $parts = array();
    if ($qs) {
        $parts[] = $qs;
    }
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            foreach ($value as $value2) {
                $parts[] = http_build_query(array($key => $value2));
            }
        } else {
            $parts[] = http_build_query(array($key => $value));
        }
    }
    return join('&', $parts);
}
like image 33
rjdown Avatar answered Jun 11 '26 21:06

rjdown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!