views:

105

answers:

3

I have a array like the bellow.

Array
(
    [1] => Array
        (           
            [TotalPosts] => 46
            [AgentSchemeNumber] => 11
            [AgentName] => Vaiji
        )

    [2] => Array
        (            
            [TotalPosts] => 3
            [AgentSchemeNumber] => 22
            [AgentName] => Vaiji
        )

    [3] => Array
        (            
            [TotalPosts] => 0
            [AgentSchemeNumber] => 33
            [AgentName] => Vicky
        )

    [4] => Array
        (            
            [TotalPosts] => 0
            [AgentSchemeNumber] => 44
            [AgentName] => Raja
        )

    [5] => Array
        (            
            [TotalPosts] => 18
            [AgentSchemeNumber] => 55
            [AgentName] => Rama
        )

    [6] => Array
        (            
            [TotalPosts] => 13
            [AgentSchemeNumber] => 66
            [AgentName] => Udaya
        )

)

Here AgentName vaiji contain 2 records. I want a output like

Array
(
    [1] => Array
        (           
            [TotalPosts] => 49
            [AgentSchemeNumber] => 11 or 22 (any number)
            [AgentName] => Vaiji
        )    

    [2] => Array
        (            
            [TotalPosts] => 0
            [AgentSchemeNumber] => 33
            [AgentName] => Vicky
        )

    [3] => Array
        (            
            [TotalPosts] => 0
            [AgentSchemeNumber] => 44
            [AgentName] => Raja
        )

    [4] => Array
        (            
            [TotalPosts] => 18
            [AgentSchemeNumber] => 55
            [AgentName] => Rama
        )

    [5] => Array
        (            
            [TotalPosts] => 13
            [AgentSchemeNumber] => 66
            [AgentName] => Udaya
        )

)

Please help me how to do it?

A: 
for ($i=0; $i < sizeof($array); $i++) for ($j=$i+1; $j < sizeof($array); $j++)
{
    if ($array[$i]['AgentName'] == $array[$j]['AgentName'])
    {
        $array[$i]['TotalPosts'] += $array[$j]['TotalPosts'];
        unset($array[$j]);
    }
}

what you want have in $array after this runs.

Svisstack
should be `$array[$i]['Name']` etc. PHP doesn't use dot notation for array or object member access.
nickf
@nickf: you are right
Svisstack
+2  A: 

Try something like this:

$array = array( /* .... */ );
$result = array();

foreach ($array as $item) {
    if (!isset($result[$item['AgentName']])) {
        $result[$item['AgentName']] = array(
             'TotalPosts'        => 0, 
             'AgnetSchemeNumber' => $item['AgentSchemeNumber'], 
             'AgentName'         => $item['AgentName'] 
        );
    }

    $result[$item['AgentName']]['TotalPosts'] += $item['TotalPosts'];
}
$result = array_values($result);

var_dump($result);
Crozin
A: 

Hi both Thank you soooooo Much. I have used Svisstack answer It's work good.You have save me. Thanks again. Nice work keep it up.

Vaiji