从现有数组创建一个新数组(php)

时间:2013-01-08 18:08:34

标签: php arrays

好的,我对C#很有经验,但对PHP很新,所以请耐心等待。

我有一个看起来有点像这样的现有数组

Array
(
[0] => Array
    (
        [author] => Gavin
        [weighting] => 2743
    )

[1] => Array
    (
        [author] => Bob
        [weighting] => 2546
    )

[2] => Array
    (
        [author] => Gavin
        [weighting] => 2227
    )
)

现在我要做的是循环,最后得到一个有两个键的新数组(GavinBob)和Bob的值是{{1虽然2546Gavin

现在我有这个几乎可以工作,但最后一个作者得到一个重复值,我无法对它进行排序?

4970

我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

这应该可以解决问题

$newarray = array();
foreach($yourarray as $a) {
    //create array if not created
    if(!isset($newarray[$a['author']])) {
        $newarray[$a['author']] = 0;
    }
    //put value in array
    $newarray[$a['author']] += $a['weighting'];
}

答案 1 :(得分:0)

$Authors = array();

foreach($array as $entry) {
    if ( array_key_exists($entry['author'], $Authors) ) {
        $Authors[ $entry['author'] ] += $entry['weighting'];
    } else {
        $Authors[ $entry['author'] ] = $entry['weighting'];
    }
}

在此处查看:[{3}}