0

suppose I have an array like this :

   Array
    (
        [0] => Array
        (
            [0] => A
            [1] => 20
        )

        [1] => Array
        (
            [0] => B
            [1] => 10
        )

        [2] => Array
        (
            [0] => G
            [1] => 5
        )

        [3] => Array
        (
            [0] => A
            [1] => 15
        )


    )

I would like to remove duplicate values and sum just a row of array : What I want :

   Array
    (
        [0] => Array
        (
            [0] => A
            [1] => 35 // <= sum : 20 + 15
        )

        [1] => Array
        (
            [0] => B
            [1] => 10
        )

        [2] => Array
        (
            [0] => G
            [1] => 5
        )



    )

I've read this question before.

updated

while($row = $stmt->fetch()){

    $arr = array(
        'GoodMainCode'=>persian_sql_to_php($row['GoodMainCode']), // <= like A in the example
        'title'=> persian_sql_to_php($row['GoodName']),
        'author'=>persian_sql_to_php($row['moalef']),
        'publisher'=>persian_sql_to_php($row['Nasher']),
        'translator'=>persian_sql_to_php($row['Motarjem']),
        'price'=>persian_sql_to_php($row['SellPrice1']),
        'isbn'=>persian_sql_to_php($row['ISBN']),
        'amount'=>persian_sql_to_php($row['Amount']), // <= if GoodMainCode is same key, I must sum it.
        'year_of_publish'=>persian_sql_to_php($row['SaleChap']),
        'period_print'=>persian_sql_to_php($row['NobateChap'])
    );


    array_push($mjson,$arr);

}



//added

foreach($mjson as $v){

    if(!isset($result[$v['GoodMainCode']]))
        $result[$v['GoodMainCode']] = $v;
    else
        $result[$v['GoodMainCode']]['amount'] += $v['amount'];
}
Community
  • 1
  • 1
S.M_Emamian
  • 17,005
  • 37
  • 135
  • 254

1 Answers1

2

This should work for you:

Just loop through your array and check if in your $result array is a key with the letter of the current inner Array from $arr. If not add it to the $result array and initialize the second key with the number.

If there is already a key with this letter you can simply add the numbers together in this array. At the end I simply use array_values() to reindex the entire array.

<?php

    foreach($arr as $v) {
        if(!isset($result[$v[0]]))
            $result[$v[0]] = $v;
        else
            $result[$v[0]][1] += $v[1];
    }

    $result = array_values($result);
    print_r($result);

?>

output:

Array
(
    [0] => Array
        (
            [0] => A
            [1] => 35
        )
    //...
    [2] => Array
        (
            [0] => G
            [1] => 5
        )

)
Rizier123
  • 58,877
  • 16
  • 101
  • 156