1

I have a multidimensional array in PHP, something that looks like:

array(array(Category => Video,
            Value => 10.99),
      array(Category => Video,
            Value => 12.99),
      array(Category => Music,
            Value => 9.99)
)

and what I would like to do is combine similar categories and output everything into a table, so the output would end up being:

<tr><td>Video</td><td>23.98</td></tr>
<tr><td>Music</td><td>9.99</td></tr>

Any suggestions on how to do this?

EDIT: I can have these in two different arrays if that would be easier.

2 Answers 2

1

A simple loop will do:

$array = [your array];
$result = array();
foreach ($array as $a) {
    if (!isset($result[$a['Category']])) {
        $result[$a['Category']] = $a['Value'];
    } else {
        $result[$a['Category']] += $a['Value'];
    }
}
foreach ($result as $k => $v) {
    echo '<tr><td>' . htmlspecialchars($k) . '</td><td>' . $v . '</td></tr>';
}
Sign up to request clarification or add additional context in comments.

Comments

1
$result = array();
foreach ($array as $value) {
  if (isset($result[$value['Category']])) {
    $result[$value['Category']] += $value['Value'];
  } else {
    $result[$value['Category']] = $value['Value'];
  }
}
foreach ($result as $category => $value)  {
  print "<tr><td>$category</td><td>$value</td></tr>";
}

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.