Search code examples
phparraysoffset

Read from group array


+---------------+-----------------+
| Type          |  Price          |
+---------------+-----------------+
| Music         |  19.99          |
| Music         |   3.99          |
| Music         |  21.55          |
| Toy           |  89.95          |
| Toy           |   3.99          |
| Phones        |  99.99          |
| Phones        |  89.99          |
+---------------+-----------------+

I have the above data displayed as below using this code:

// Get the sum
$group = array();
foreach($rows as $r){
  $group[$r->type] = $group[$r->Type] + $r->Price;
}

// Display
foreach($group as $type=>$price){
  echo "Type:".$type." Price: ".$price;
}

Result:

Music  | 45.53
Toy    | 93.94
Phones | 189.98

My problem is how to display the data from the array ($group) starting from the second record and also how to display just one record from the array.


Solution

  • Try using array_slice();

    //this will create new array without first element
    $new_group = array_slice($group, 1);
    

    And now iterate over $new_group as before.