0

I have an associative array that looks like this:

Array (
    [0] => Array (
        [amount] => 3
        [name] => Chuck
    )
    [1] => Array (
        [amount] => 2
        [name] => Steve
    )
    [2] => Array (
        [amount] => 5
        [name] =>
    )
    [3] => Array (
        [amount] => 4
        [name] => Chuck
    )
    [4] => Array (
        [amount] =>
        [name] => Chuck
    )
)

I need to remove values that are missing a name or amount e.g. [2] and [4] and then sum the totals for each name so that the final array is:

Array (
    [0] => Array (
        [amount] => 7
        [name] => Chuck
    )
    [1] => Array (
        [amount] => 2
        [name] => Steve
    )
) 
1
  • Have you tried to code it? Commented Mar 30, 2013 at 2:36

2 Answers 2

2

For anyone looking for this nowadays, this would be much cleaner:

$sum = array_sum(array_column($data, 'amount'));
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

$starting_array = array( ... ); // Initial array with your setup
$final_array = array();
$sum = 0;

foreach ($starting_array as $idx => $data) {
  if (!empty($data['amount']) && !empty($data['name'])) {
    $final_array[$idx] = $data;
    $sum += $data['amount'];
  }
}

// After looping through all of the items, $final_array should contain all
// of the specific items that have an amount and name set. In addition, the
// total of all of the amounts will be in $sum.

Take a look at php's empty(). Note: If 0 is an allowed value, you may want to use is_null() instead.

5 Comments

Thanks Aiias, that worked for cleaning up the array. What does $idx = $data do? Is this similar to $key = > $value? Also, do you have any advice for summing the values for each name? Thanks again.
@CameronMacfarlane - In a php foreach loop, you loop through all of the items in the array. When you use the syntax foreach ( $ARRAY as $KEY => $VALUE ) you will get the key of each item and its corresponding value (at that key: e.g. $ARRAY[$KEY] = $VALUE for every $KEY). I would definitely recommend looking further into php's foreach for a more complete explanation. In terms of summing the values for each name, check my edit.
Hi Aiias, thanks again. I understand how $key => $value works in a foreach loop. I was just asking is $idx=> $data is the same, I have never seen this syntax. Also, I wanted to sum values for each name, opposed to the total of all. I tried the edit, it didn't work for summing the names amount.
I think I found my answer here stackoverflow.com/questions/14195916/…
@CameronMacfarlane - Yup, that is definitely another way to do it.

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.