Robert Ursărescu
Robert Ursărescu

Reputation: 81

Adding multiple values to same key in array php

I want to add multiple values into arrays, for same key. I have this code:

    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;
}

Here I have for example: seller 1 with values: 100 and 101 Seller 2 with values: 107

But on my code, on seller 1 for example, is showing only last value 101, but not both. What is wrong ?

And the call code:

    $call = $this->cart->getOnlySellers();
        
        foreach ($call as $seller => $products)
        {
        
            $show = "$show <br> $seller has value $products";


        }

Thanks!

Upvotes: 1

Views: 2060

Answers (1)

zeterain
zeterain

Reputation: 1140

You could add an array of product ids to your $sellers array, allowing you to assign multiple product_ids to each seller. This [] operator will push the $product_id onto a new array at $sellers[$getseller].

$sellers[$getseller][] = $product_id;

The full code then being:

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;
}

When you output the values, you could use implode to glue the product ids together:

$call = $this->cart->getOnlySellers();
foreach ($call as $seller => $products)
{
    $show = "$show <br> $seller has value ".implode(', ', $products);
}

Upvotes: 1

Related Questions