[英]Adding multiple values to same key in array php
我想为相同的键将多个值添加到数组中。 我有这个代码:
public function getOnlySellers()
{
$sellers[] = array();
foreach ($this->getProducts() as $product) {
$product_id = $product['product_id'];
$getseller = $this->getSellerbyProduct($product_id);
$sellers[$getseller] = $product_id;
}
return $sellers;
}
这里我有例如:卖家 1 的值:100 和 101 卖家 2 的值:107
但是在我的代码中,例如在卖家 1 上,只显示最后一个值 101,但不能同时显示两者。 怎么了 ?
和调用代码:
$call = $this->cart->getOnlySellers();
foreach ($call as $seller => $products)
{
$show = "$show <br> $seller has value $products";
}
谢谢!
您可以将一系列产品 ID 添加到$sellers
数组,从而允许您为每个卖家分配多个 product_id。 这个[]
运算符会将$product_id
推送到$sellers[$getseller]
处的新数组中。
$sellers[$getseller][] = $product_id;
完整的代码是:
public function getOnlySellers()
{
$sellers[] = array();
foreach ($this->getProducts() as $product) {
$product_id = $product['product_id'];
$getseller = $this->getSellerbyProduct($product_id);
$sellers[$getseller][] = $product_id;
}
return $sellers;
}
当您输出值时,您可以使用implode
将产品 ID 粘合在一起:
$call = $this->cart->getOnlySellers();
foreach ($call as $seller => $products)
{
$show = "$show <br> $seller has value ".implode(', ', $products);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.