Gavin Mannion
Gavin Mannion

Reputation: 905

Creating a new Array from an existing Array (php)

Okay I'm quite experienced with C# but am very new with PHP so please bear with me.

I have an existing array that looks a bit like this

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

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

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

Now what I want to do is loop through that and end up with a new array that has 2 keys (Gavin and Bob) and Bob's value is 2546 while Gavin's is 4970.

Right now I have this which nearly works but the last author gets a duplicate value and I can't sort it?

if (array_key_exists($authorName, $Authors)) {
    foreach ($Authors as $key_name => &$key_value) {
        if ($key_name == $authorName)
        {
                $key_value = $key_value + $weight;
        }
    }
}
else {
    $Authors[$authorName] = $weight;
}

What am I doing wrong here?

Upvotes: 0

Views: 1216

Answers (2)

Philippe Boissonneault
Philippe Boissonneault

Reputation: 3949

This should do the trick

$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'];
}

Upvotes: 2

Joseph Silber
Joseph Silber

Reputation: 219930

$Authors = array();

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

See it here in action: http://codepad.viper-7.com/LUx1r5

Upvotes: 0

Related Questions