Reputation:
I have an array like the following:
$quantity = explode(",", $dataProducts["quantityArray"]);
$valuePrice = explode(",", $dataProducts["valuePriceArray"]);
$productsId = explode(",", $dataProducts["productsIdArray"]);
for($i=0;$i<count($productsId);$i++){
$products = array('id' => $productsId[$i],
'price' => $valuePrice[$i],
'quantity' => $quantity[$i]);
}
Suppose the vector is composed of 4 products with their id, prices and quantities. (Previously I check that the array is properly armed)
$products[0] = ['id' => 4, 'price' => 20, 'quantity' => 2]
$products[1] = ['id' => 10, 'price' => 100, 'quantity' => 5]
$products[2] = ['id' => 15, 'price' => 40, 'quantity' => 4]
$products[3] = ['id' => 20, 'price' => 50, 'quantity' => 3]
And I'm passing it as a parameter to the url of 'success'. But when the url is generated, only the first index of the array arrives.
$products= http_build_query($products);
#Configure the url of response for user
$preference->back_urls = array(
"success" => "{$url}/index.php?route=profile&data=".$products,
"failure" => "{$url}/index.php?route=error",
"pending" => "{$url}/index.php?ruta=pending"
);
Example of generated url, with only the first index of the array:
https://www.webpage.com/index.php?route=profile&data=id=4&price=20&quantity=2
What am I doing wrong?
Upvotes: 0
Views: 627
Reputation: 4219
This:
$products[0] = ['id' => 4, 'price' => 20, 'quantity' => 2];
$products[1] = ['id' => 10, 'price' => 100, 'quantity' => 5];
$products[2] = ['id' => 15, 'price' => 40, 'quantity' => 4];
$products[3] = ['id' => 20, 'price' => 50, 'quantity' => 3];
$str = http_build_query($products);
echo $str . PHP_EOL;
Generates this:
0%5Bid%5D=4&0%5Bprice%5D=20&0%5Bquantity%5D=2&1%5Bid%5D=10&1%5Bprice%5D=100&1%5Bquantity%5D=5&2%5Bid%5D=15&2%5Bprice%5D=40&2%5Bquantity%5D=4&3%5Bid%5D=20&3%5Bprice%5D=50&3%5Bquantity%5D=3
If you are looking for output like this:
id=4&price=20&quantity=2&id=10&price=100&quantity=5&id=15&price=40&quantity=4&id=20&price=50&quantity=3
Then do this:
$str2 = '';
foreach($products as $product) {
$tmp = http_build_query($product);
if ( ! empty($str2) ) {
$str2 .= '&';
}
$str2 .= $tmp;
}
echo $str2 . "\n";
You could encode the entire array as JSON base 64 encoded.
$data = base64_encode(json_encode($products));
echo "http://example.com/?data=" . $data . PHP_EOL;
Then on the receiving end:
$products = json_decode(base64_decode($_GET['data']), true);
Upvotes: 0
Reputation: 3231
In order to append an item to an array, use the following syntax: $array[] = $value
In your example:
for($i=0; $i<count($productsId); $i++){
$products[] = array(
'id' => $productsId[$i],
'price' => $valuePrice[$i],
'quantity' => $quantity[$i]
);
}
Upvotes: 1