简体   繁体   中英

PHP Create querystring from multidimensional array without using loop

I have a multidimensional array. Like this.

Array
(
    [38] => Array
        (
            [quantity] => 1
            [price] => 149
            [product_code] => 4578425
        )

    [39] => Array
        (
            [quantity] => 2
            [price] => 300
            [product_code] => 4578426 
        )

)

I want to create query string from these values like

https://www.domain.com/checkout.php?PRODS=4578425,4578426&QTY=1,2&CART=1

Without using loops...

I don't think AFAIK, it is possible, since you have arrays in array, so using implode won't help. But, using loops, yea.

Use this code:

$prods = array();
$qty = array();
foreach ($array as $item)
{
    $prods[] = $item["product_code"];
    $qty[] = $item["quantity"];
}
echo 'https://www.domain.com/checkout.php?PRODS=', implode(',', $prods),'&QTY=', implode(',', $qty),'&CART=1';

you can use implode() method

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone

Yes i think there is a way,

You can use serialize to put it in a string and then unserialize to get it back to an array like this:

<?php

 $arr = Array
(
38 => Array
    (
        'quantity' => 1,
        'price' => 149,
        'product_code' => 4578425
    ),

39 => Array
    (
        'quantity' => 2,
        'price' => 300,
        'product_code' => 4578426 
    )

);


$newarr = 'https://www.domain.com/checkout.php?string=';
$newarr .= serialize($arr);

?>

then you have this result:

https://www.domain.com/checkout.php?string=a:2 :{i:38;a:3:{s:8:"quantity";i:1;s:5:"price";i:149;s:12:"product_code";i:4578425;}i:39;a:3:{s:8:"quantity";i:2;s:5:"price";i:300;s:12:"product_code";i:4578426;}}a:2:{i:38;a:3:{s:8:"quantity";i:1;s:5:"price";i:149;s:12:"product_code";i:4578425;}i:39;a:3:{s:8:"quantity";i:2;s:5:"price";i:300;s:12:"product_code";i:4578426;}}

No loops but it is not pretty!!!

If you wish to use this inside url I have to warn you. The url get method is only intended for short information like id's or other key values. If your url gets over 2000 characters most web-servers would have problems with it. Not sure if that was your intention.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM