开发者

How to create a collection of multi dimensional arrays and not overwrite original values when new ones are pushed

Here is my site http://69.231.195.173:8888/iadprint/products?product=flyers

When the user selects a few selections that relate to the flyer product and presses add to cart. this is what code is executed.

if(isset($_POST['btnAddToCart']) && isset($_GET['product']))
    {
        $product_id = $action->getProductID($_GET['product']);

        $attribute[$prod开发者_Python百科uct_id] = array();


        foreach ($_POST as $field=>$hash) 
        {
            $hash = $security->clean_numeric($hash);

            if($field != "btnAddToCart" && $field != 'price' && !empty($hash))
            {
                array_push($attribute[$product_id], $hash);

            }
        } 

        $_SESSION['iadprint_cart'] = $attribute;
}

the array that gets formed looks like this

Array
(
    [10] => Array
        (
            [0] => 30
            [1] => 36
        )
)

inside that main array the 10 refers to flyer product id name. inside of that the 30 and 36 are the ids of the selections.

the problem i'm having is if you select business card and make your selections and add to cart instead of pushing in a format like the picture that is everything inside the array() for the new product. the data gets overridden. I am using array_push and it should work but it is not.


Solution:

If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator:

$a = array(10 => array(25,26));
$b = array(22 => array(45,66));
$c = $a + $b;
print_r($c);

Output:

Array
(
    [10] => Array
        (
            [0] => 25
            [1] => 26
        )

    [22] => Array
        (
            [0] => 45
            [1] => 66
        )
)

The keys are preserved in this case.

Same answer from the other question you posted relating this issue: merging a multi-dimensional array into another multi-dimensional array


I think this will be useful in_array().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜