开发者

How to add values in multidimensional array?

开发者 https://www.devze.com 2022-12-28 23:54 出处:网络
I have a array like the bellow. Array ( [1] => Array ( [TotalPosts] => 46 [AgentSchemeNumber] => 11

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
            [AgentSche开发者_开发知识库meNumber] => 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?


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);


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.

0

精彩评论

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