0

I have the array shown below. I would like to have a resultant array where value in the key elements [tv], [tu], [cost], [km] are summed for all the row with same value of [tick_id]. In this example we should sum the value [tv], [tu], [cost], [km] of the array elements 0, 1, 2, … How can I do this?

Array (
    [0] => stdClass Object (
        [id] => 15
        [user_id] => 44
        [name] => inspector1
        [tv] => 0.00
        [tc] => 0.00
        [tu] => 0.00
        [cost] => 0.00
        [kms] => 0
        [date_s] => 2012-03-30
        [notes] =>
        [tick_id] => 11
        [tot_fee] => 5500
    )
    [1] => stdClass Object (
        [id] => 39
        [user_id] => 46
        [name] => Assistant
        [tv] => 10.00
        [tc] => 0.00
        [tu] => 4.50
        [cost] => 0.00
        [kms] => 120
        [date_s] => 2012-03-31
        [notes] =>
        [tick_id] => 15
        [tot_fee] => 0
     )
    [2] => stdClass Object (
        [id] => 35
        [user_id] => 46
        [name] =>
        [tv] => 0.00
        [tc] => 0.00
        [tu] => 0.00
        [cost] => 0.00
        [kms] => 0
        [date_s] => 2012-03-30
        [notes] =>
        [tick_id] => 13
        [tot_fee] => 3200
    )
    …
)
2
  • It is possible. Have you tried using foreach to iterate and sum? Commented Apr 4, 2012 at 7:42
  • use var_export to export data structures rather than print_r. TYIA Commented Apr 4, 2012 at 7:45

1 Answer 1

1

It's hard to tell with the way your code is displaying but this should be what you need:

// Create the cost total array
$cost = array();

// Iterate over each object in the given array
foreach ($array as $object)
{

  // If the tick_id has not yet been assigned as a key then do so with a default cost of 0
  if (!isset($cost[$object->tick_id]))
  {
    $cost[$object->tick_id] = 0;
  }

  // Increment the total cost for the given tick_id
  $cost[$object->tick_id] += $object->tv + $object->km + $object->tu + $object->cost;

}

$cost will be an array where the key is the tick_id and the value is the total cost.

Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks, great suggestion, you solved all my problems!! :)

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.