Vinai Raj
Vinai Raj

Reputation: 151

generate array for query string in php

Here I want to create an array for query string like given below:

item[]['item_id']=I00001&item[]['rate']=10.52&item[]['qty']=2&
item[]['item_id']=I52124&item[]['rate']=15.00&item[]['qty']=1&
item[]['item_id']=I62124&item[]['rate']=8.20&item[]['qty']=5

I want to generate it dynamically.

for($i = 0 ; $i< count($allitems) ;$i++){
    $itemid =  explode('~',$allitems[$i]);
    $arrdet[]=["'item_id'"=>$itemid[0],"'rate'"=>$itemid[1],"'qty'" =>$itemid[2]];  
    $item['item'] = array_merge($arrdet);
    //$item['item'][]=["'item_id'"=>$itemid[0],"'rate'"=>$itemid[1],"'qty'" =>$itemid[2]];
} 
echo  http_build_query($item);

but my result for this

item[0]['item_id']=I00001&item[0]['rate']=10.52&item[0]['qty']=2&   
item[1]['item_id']=I52124&item[1]['rate']=15.00&item[1]['qty']=1&
item[2]['item_id']=I62124&item[2]['rate']=8.20&item[2]['qty']=5

How it Possible? Thanks in advance

Upvotes: 0

Views: 58

Answers (2)

Chay22
Chay22

Reputation: 2894

I did so much workarounds. But, it should actually works.

$countAllitems = count($allitems);
$arr = array();
$items = array();
$query = array();
for($i = 0 ; $i< $countAllItems; $i++){
    $itemid =  explode('~',$allitems[$i]);

    $arr['item_id'] = $itemid[0];
    $arr['rate'] = $itemid[1];
    $arr['qty'] = $itemid[2];

    //Assign the array to another array with key 'item[]'
    $items['item[]'] = $arr;

    //Build the array to http query and assign to another array
    $query[] = http_build_query($items);
}

//Implode the stored http queries
echo implode('&', $query);

Upvotes: 1

Finwe
Finwe

Reputation: 6745

The array is zero-indexed internally.

$array = [1, 2, 3];

is internally

$array = [
    0 => 1,
    1 => 2,
    2 => 3
]

The http_build_query will always output keys of the array, even if you do not specify them explicitly.

Upvotes: 0

Related Questions