Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill Values in multidimensional Array (PHP)

Tags:

arrays

php

I've got a small problem. I'm working on a little package/product-list. If you're watching a Package, my website should show you which products are in there. If a product is more than one time in it, the array should be deleted and the value of the leftover array should be + 1 (each deleted array).

So here's my code:

// $products_in_package has all products in it
// First of all, the products come from a db and don't have a count
// So i first give them a count of 1

foreach ($products_in_package as $product => $value) {
    $products_in_package[$product]['count'] = intval(1);
}

foreach ($products_in_package as $product) {
    $id_to_find = intval($product['ID']);
    $product_count = intval($product['count']);
    $found_id = 0;
    // Now I try to find any ident products
    // If found and over 1 time (beacouse he finds the first too of course)
    // Then delete this array and count up the products count

    for ($i=0; $i <= count($products_in_package); $i++) {
        if(intval($products_in_package[$i]['ID']) === $id_to_find){
            $found_id++;

            if($found_id > 1){
                $product_count = $product_count + 1;
                $product['count'] = $product_count;
                unset($products_in_package[$i]);
                array_merge($products_in_package);

                while($i > $products_in_package){
                    $i = 0;
                }
            }
        }
    }
}

What I'm getting is the correct multidimensional array but the count is still 1. What's wrong with the code?

Everytime I try to log the code i'm getting the right integer. (No, I already tried to delete the chache) But if I log the array out of the loops, I get always the count of 1.

like image 814
Da Flo Avatar asked May 06 '26 02:05

Da Flo


1 Answers

$product is a copy of the array element, so when you do $product['count'] = $product_count you're assigning to a copy, not the original array.

You can fix this by using a reference in the foreach:

foreach ($products_in_package as &$product) {
like image 112
Barmar Avatar answered May 08 '26 15:05

Barmar