1

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!

3
  • When you add your product id into the $sellers array, you are overwriting any previous entry. You could append the new product_id instead. Commented Nov 20, 2020 at 13:50
  • I know that, but how can I do without overwriting ? I can have multiple values for same key ? Commented Nov 20, 2020 at 13:52
  • Store an array under that key and you can have multiple values. Commented Nov 20, 2020 at 14:25

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.