views:

268

answers:

3

So I have this sample string:

?items=3744130|1^356221|2^356222|1

extracted from a URL:

http://www.example.com/process.php?items=3744130|1^356221|2^356222|1

I need to convert it into this, and for the life of me I'm getting stuck.

?items=model_1=3744130&qty_1=1&model_2=356221&qty_2=2&model_3=356222&qty_3=1

I've gotten this far but that's it.

$url = substr($_SERVER['QUERY_STRING'],6); 
$query = explode('^', $url); 
echo http_build_query($query, 'model_');

Output currently is:

model_0=1234435%7C9&model_1=56788%7C9&model_2=6758765%7C9&model_3=3736543%7C9

How can I get the first set to be model_1 instead of the default model_0?

Thanks

A: 

A quick patch should be

....
$url = substr($_SERVER['QUERY_STRING'],6);
$query = explode('^', $url);

array_unshift($query,'placeholder');
$result=http_build_query($query, 'model_');
$result = substr($result, 19);
....
Eineki
A: 

Try this:

$items = explode('^', $_GET['items']);
$query = '';
foreach ($items as $key => $val) {
    list($model, $qty) = explode('|', $val);
    $query .= '&model_'.($key+1).'='.urlencode($model);
    $query .= '&qty_'.($key+1).'='.urlencode($qty);
}
echo substr($query, 1);
Gumbo
+1  A: 

You need to build the array with keys before passing it to http_build_query() if you want the numbering to start with 1.

$arr = array();
$count = 1;

foreach (explode('|', $_GET['items']) as $item) {
  $elements = explode('^', $item);
  if (count($elements) == 1) {
    $arr["model_$count"] = $elements[0];
    $arr["qty_$count"] = 1;
  }
  else {
    $arr["model_$count"] = $elements[1];
    $arr["qty_$count"] = $elements[0];
  }
  $count++;
}

$query = http_build_query($arr);
Lukman