0

In php I have the following array:

$car[] = array ("id"=>"1", "brand"=>"Audi", "price"=>"7000"); 
$car[] = array ("id"=>"9", "brand"=>"Merc", "price"=>"9000");

With this array I would like to build the following query string:

&brand0=Audi&brand1=Merc&id0=1&id1=9&price0=7000&price0=9000

How can I go about doing this?

Please note that the array may have more results than just the 2 rows, and so that the built querystring should be able to cope with it (also the results being used in this example may vary).

Thanks

0

4 Answers 4

3

As alternative you could use http_build_query. And to further simplify I would propose:

$url = http_build_query(array("car" => $car));

Which will result in such an URL parameter list instead:

&car[0][brand]=Audi&car[1][brand]=Merc&car[0][id]=1&car[1][id]=9&car[0][price]=7000&car[1][price]=9000

Which looks odd, but allows PHP to reconstruct your two arrays as-is.

Sign up to request clarification or add additional context in comments.

2 Comments

And will make processing it in your script much easier as well.
Nice one, didn't know this :)
2

Loop through the array, and put key-value pairs in another array. Then finally implode the array. Something like:

$data = array();
$i = 0;
foreach ($car as $k=>$v)
{
   $data[] = $k . '_' . $i .'=' . $v;
   $i++;
}
echo implode('&', $data);

I usually use implode because AFAIK it's faster than $data +=.

EDIT

Actually, that one above works for only 1 array. Here is for multiple arrays:

$data = array();
$i = 0;
foreach ($car as $c)
{
   foreach ($c as $k=>$v);
      data[] = $k . '_' . $i . '=' . $v;
   $i++;
}
echo implode ('&', $data);

Comments

0
$params = array();
for($i=0;$i<count($car);$i++) {
    $params[] = 'id' . $i . '=' . $car[$i]['id'];
    $params[] = 'brand' . $i . '=' . $car[$i]['brand'];
    $params[] = 'price' . $i . '=' . $car[$i]['price'];
}
$string = implode('&', $params);

This will go through, and create the keys with the number on them, and then glue it all together at the end to give you the $string that you were wanting. It will also, just for cleanliness, not have an extra & at the start or end that you might get if you simply append.

Comments

0

Perhaps not the most elegant way.

$str = "";
foreach($car as $key => $val){
    $str .= "$key=$val&";
}
$str = substr($str, 0, strlen($str) - 2);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.