2

I have this array and I like to group the score per newname and sum. I have a input array which looks like:

Array
(
    [0] => Array
        (
            [newname] => Horse
            [score] => 4
        )

    [1] => Array
        (
            [newname] => Horse
            [score] => 2
        )

    [2] => Array
        (
            [newname] => Snake
            [score] => 3
        )

    [3] => Array
        (
            [newname] => Dog
            [score] => 3
        )
)

and I need the output array to sum the score per newname. So this would be the outcome:

Array
(
    [0] => Array
        (
            [newname] => Horse
            [score] => 6
        )

    [1] => Array
        (
             [newname] => Snake
            [score] => 3
        )

    [2] => Array
        (
             [newname] => Dog
            [score] => 3
        )
)

For this I have the following php

$newArray = array();
foreach ($arrayAnimals as $row){
    if(!isset($newArray[$row['newname']]['score'])){
        $newArray[$row['newname']]['score'] =0;
    }
    $newArray[$row['newname']]['score'] += $row['score'];
}

But it displays only the scores?

4 Answers 4

7

You can do it like this

$newArray = array();
foreach ($arrayAnimals as $row){
    $animal = $row['newname'];
    if(!isset($newArray[$animal])){
        $newArray[$animal]['newname'] = $animal;
        $newArray[$animal]['score'] = 0;
    }
    $newArray[$animal]['score'] += $row['score'];
}
print_r(array_values($newArray));
Sign up to request clarification or add additional context in comments.

2 Comments

tx can you explain me this part ` $newArray[$newname] = array( 'newname' => $row['newname'],`
You just push a new array inside $newname key with the details of the animal. See clearer updated answer
2

You can loop like:

    $newArray = array();
    foreach( $arr as $value ) {
        //If newname does not exist, assign the value
        if ( !isset( $newArray[ $value[ 'newname' ] ] ) ) $newArray[ $value[ 'newname' ] ] = $value;

        //If newname exist, add the value
        else $newArray[ $value[ 'newname' ] ][ 'score' ] += $value[ 'score' ];
    }

    //Convert an associative array to a simple array of its values...
    $newArray = array_values( $newArray );

This will result to:

Array
(
    [0] => Array
        (
            [newname] => Horse
            [score] => 6
        )

    [1] => Array
        (
            [newname] => Snake
            [score] => 3
        )

    [2] => Array
        (
            [newname] => Dog
            [score] => 3
        )

)

Comments

1

Input

$array = array(
    array('newname' => 'Horse','score' => 4),
    array('newname' => 'Horse','score' => 2),
    array('newname' => 'Snake','score' => 3),
    array('newname' => 'Dog','score' => 3)
);

Solution

$new = array();
foreach($array as $r){
    //$r['newname'] contains name of animal. below condition check the current animal is in new array or not.
    if(!isset($new[$r['newname']]))$new[$r['newname']] = $r;//if not. insert animal's array in new array
    else $new[$r['newname']]['score'] = ($r['score']+$new[$r['newname']]['score']);// if yes, add the score of animal saved in new array to current score of that animal.
}
echo "<pre>";print_r($new); // show you the output.

Output

Array
(
    [Horse] => Array
        (
            [newname] => Horse
            [score] => 6
        )

    [Snake] => Array
        (
            [newname] => Snake
            [score] => 3
        )

    [Dog] => Array
        (
            [newname] => Dog
            [score] => 3
        )

)

Comments

0

You can also do this:

$animalArray = array( array('newname' => 'Horse','score' => 4),
                      array('newname' => 'Horse','score' => 2),
                      array('newname' => 'Snake','score' => 3),
                      array('newname' => 'Dog','score' => 3),
                      array('newname' => 'Snake','score' => 7),
                      array('newname' => 'Snake','score' => 8),
                      array('newname' => 'Bat','score' => -1),
                      array('newname' => 'Dragon','score' => 70),
                      array('newname' => 'Bat','score' => 80)
                    );


$found = array();   // array to store each animals index
$counter = 0;       // current index

foreach ($animalArray as $thisRow)
{
    $animalName = $thisRow['newname'];

    // if the animal has not yet been found, add it
    if(!isset($found[$animalName]))
    {
        $newIndex = $counter;                        // current index
        $found[$animalName] = array();
        $found[$animalName]['index'] = $newIndex;    // store the index for this animal
    }
    else
    {
        $index = $found[$animalName]['index'];                // get the stored index
        $animalArray[$index]['score'] += $thisRow['score'];   // add current score
        unset($animalArray[$counter]);                        // remove the duplicate
    }
    $counter++;
}

print_r($animalArray);

Outputs:

Array ( [0] => Array ( [newname] => Horse [score] => 6 ) 
        [2] => Array ( [newname] => Snake [score] => 18 ) 
        [3] => Array ( [newname] => Dog [score] => 3 ) 
        [6] => Array ( [newname] => Bat [score] => 79 ) 
        [7] => Array ( [newname] => Dragon [score] => 70 )
      )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.