如何在多维数组中添加值?

时间:2010-05-05 07:30:01

标签: php multidimensional-array

我有一个像下面的阵列。

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
        )

)

此处,AgentName vaiji包含2条记录。我想要像

这样的输出
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
        )

)

请帮我怎么做?

2 个答案:

答案 0 :(得分:2)

尝试这样的事情:

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

答案 1 :(得分:1)

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

运行后你想在$ array中得到什么。