Here is my array:
$a = array(
“1” => “3”,
“1” => “2”,
“2” => “1”,
“1” => “2”,
“2” => “2”,
);

and my expected output is :
1 = 7 , 2 = 3

How can I do that in foreach?

Recommended Answers

All 17 Replies

$b = array ();
foreach ($a as $key => $value)
{
    if (isset($b[$key]))
    {
        $b[$key] += $value;
    }
    else
    {
        $b[$key] = $value;
    }
}
print_r($b);

Assume this array is "merchantcode" => "productID" . I've another variable which is quantity($q) which submit by user in cart.

Can I do something like this?

$a = array(
“1” => “3” * $q,
“1” => “2” * $q,
“2” => “1” * $q,
“1” => “2” * $q,
“2” => “2” * $q,
);

This is the code:

$array = array(
"1" => "3",
"1" => "3",
"3" => "3",
"2" => "3",
"1" => "3",
);

$b = array ();
foreach ($array as $key => $value)
{
    if (isset($b[$key]))
    {
        $b[$key] += $value;
    }
    else
    {
        $b[$key] = $value;
    }
}
print_r($b);

And the output is Array ( [1] => 3 [3] => 3 [2] => 3 ) instead of Array ( [1] => 9 [3] => 3 [2] => 3 ). Please help

Try this, you'll see the issue:

$array = array(
    "1" => "3",
    "1" => "3",
    "3" => "3",
    "2" => "3",
    "1" => "3"
);
print_r($array);

You are overwriting your array because you're re-using the same key.

So any solution?Because I'm using mysql_fetch_array and store the variable.

$sql = mysql_query("SELECT Shop,Weight FROM product WHERE ID = '".$pid."'");
                    while($row = mysql_fetch_array($sql)){
                    $array = array(
                    $row['Shop'] => $row['Weight']
                    );
                    }

So it become :

$array = array(
    "1" => "3",
    "1" => "3",
    "3" => "3",
    "2" => "3",
    "1" => "3"
);

Store them differently.

$row[] = array ('Shop' = > $row['Shop'], 'Weight' => $row['Weight']);

After I change to this

    $sql = mysql_query("SELECT ShopID,Weight FROM w_product WHERE ID = '".$pid."'");
                    while($row = mysql_fetch_array($sql)){
                    $array[] = array(
                    "Shop" =>$row['ShopID'],
                     "Weight" => $row['Weight']*$q
                    );
                    }

foreach($array as $arr)
        {
            foreach($arr as $a => $val){
                if(isset($result[$a])){
                    $result[$a] += $val;
                }else{
                $result[$a] = $val;
                }
            }
        }

Array look like :
Shop => 3,
Weight =>4

Shop=> 3,
Weight =>5

Shop=> 3,
Weight =>1

THe output become Shop=9 , weight =10. How to make it Shop =3,Weight =10?

And I want to pass only "Shop" to a function is that possible?

foreach($array as $item)
{
    if (isset($result[$item['Shop']]))
    {
        $result[$item['Shop']] += $val;
    }
    else
    {
        $result[$item['Shop']] = $val;
    }
}

Now the output become

 Array
(
    [] => Array
        (
            [Shop] => 4
            [Weight] => 642
        )

)

instead of

Array
(
    [] => Array
        (
            [Shop] => 4
            [Weight] => 3
        )

        Array
        (
            [Shop] => 3
            [Weight] =>1
        )

)

it only display 1 array record only.

Try this (works for me):

<pre>
<?php
$array = array (
    array ('Shop' => 3, 'Weight' => 4),
    array ('Shop' => 3, 'Weight' => 5),
    array ('Shop' => 3, 'Weight' => 1)
);
print_r($array);

$result = array ();
foreach($array as $item)
{
    if (isset($result[$item['Shop']]))
    {
        $result[$item['Shop']] += $item['Weight'];
    }
    else
    {
        $result[$item['Shop']] = $item['Weight'];
    }
}

print_r($result);

Oh my GOD! Yes. Thank you. THis is exactly what I want. Really thanks!!!!

Can I ask 1 more question?

I've a database table (shippingcharges) and the attribute is ID,Price

ShippingCharges(for example this is the shipping rate for shop 4)

ID   | Price                              | Shop
1    | 0.5:7,1.0:9,1.5:12,2.0:14,2.5:18   | 4

(price format : 0.5:7 mean 0.5kg = 7 dollar,1.0:9 mean 1kg = 9 dollar)

I want to create a function which is determine the item weight then show the price base on the shop id and weight above(from the code you provide) but I don't know how to do it.

I can use function getPrice( $result[$item['Shop']]) to pass the shop id?

        function shippingRate($shopid,$weight){
            $shopid = intval($shopid);
            $weight = floatval($weight);
            $list = array();
            $sql = mysql_query("SELECT Rate FROM hippingrate WHERE Shop = '".$shopid."'");
            $count = mysql_num_rows($sql);
            if ($count> 0){
            while($row = mysql_fetch_array($sql)){
            $rate = explode(",",$row['Rate']);

            foreach($rate as $r){
                $list[] = $r;
            }


            }
            }
        }

And now this is my print_r result:

Array ( [0] => Array ( [0] => 0.5 [1] => 7 ) [1] => Array ( [0] => 1.0 [1] => 9 ) [2] => Array ( [0] => 1.5 [1] => 11 ) [3] => Array ( [0] => 2.0 [1] => 13 ) [4] => Array ( [0] => 2.5 [1] => 16 ) [5] => Array ( [0] => 3.0 [1] => 18 ) [6] => Array ( [0] => 3.5 [1] => 21 ) [7] => Array ( [0] => 4.0 [1] => 24 ) )

I'm devide the sentence from "0.5:7,1.0:9,1.5:11,2.0:13,2.5:16,3.0:18,3.5:21,4.0:24" to become array above. How can I determine whether $weight is bigger and smaller to which number and return the price ?

How can I determine whether $weight is bigger and smaller to which number and return the price ?

Loop through the array until the weight value is larger than the current indicated weight.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.