我有一个如下数组:
$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]);
}
假设向量由4个产品组成,它们的ID,价格和数量。 (以前,我检查阵列是否已正确设防)
$ products [0] = ['id'=> 4,'价格'=> 20,'数量'=> 2]
$ products [1] = ['id'=> 10,'价格'=> 100,'数量'=> 5]
$ products [2] = ['id'=> 15,'价格'=> 40,'数量'=> 4]
$ products [3] = ['id'=> 20,'价格'=> 50,'数量'=> 3]
我将其作为参数传递给“成功”的网址。 但是当生成url时,只有数组的第一个索引到达。
$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"
);
生成的url示例,仅包含数组的第一个索引:
https://www.webpage.com/index.php?route=profile&data=id=4&price=20&quantity=2
我在做什么错了?
答案 0 :(得分:2)
为了将项目追加到数组,请使用以下语法:$array[] = $value
在您的示例中:
for($i=0; $i<count($productsId); $i++){
$products[] = array(
'id' => $productsId[$i],
'price' => $valuePrice[$i],
'quantity' => $quantity[$i]
);
}
答案 1 :(得分:1)
此:
$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;
生成此:
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
如果您正在寻找这样的输出:
id=4&price=20&quantity=2&id=10&price=100&quantity=5&id=15&price=40&quantity=4&id=20&price=50&quantity=3
然后执行以下操作:
$str2 = '';
foreach($products as $product) {
$tmp = http_build_query($product);
if ( ! empty($str2) ) {
$str2 .= '&';
}
$str2 .= $tmp;
}
echo $str2 . "\n";
您可以将整个数组编码为JSON base 64编码。
$data = base64_encode(json_encode($products));
echo "http://example.com/?data=" . $data . PHP_EOL;
然后在接收端:
$products = json_decode(base64_decode($_GET['data']), true);