3

Hi I am new to php and I faced some problem when I need sum up array in foreach.

I had array like this:

  $arrays = [
                [
                      'orderid' => "1",
                      'price' => "100"
                      'rate' => "1"
                ],
                [
                      'orderid' => "2",
                      'price' => "200"
                      'rate' => "5"
                ],

       ];

What I face when I using foreach, the price * rate will sum continuously but not sum up separately.

     $bonus = array();
     foreach($arrays as $data){
           $bonus = $data['originalPrice'] * $data['rate'];
       }

I also tried using array_map() but also cannot get my answer;

WHat I need about :

$array = [
[
   'total' => 100;
],
[
   'total' => 1000;
]


]

Any idea for help?

UPDATED: ALL THE ANSWER ARE CORRECTED, is the api data give me wrong info lol.

2
  • You could use array_push() function inserts one or more elements to the end of an array. Commented Sep 26, 2019 at 8:27
  • Just use $bonus[] = instead of $bonus = . Commented Sep 26, 2019 at 8:28

3 Answers 3

1
 foreach($arrays as $data){
       $bonus[]['total'] = $data['price'] * $data['rate'];
   }
  print_r($bonus);
Sign up to request clarification or add additional context in comments.

1 Comment

still the same it will continue add
0

You are using price so use that property and you need to push the value in the result array. Thus, you need to do:

<?php
$arrays=array(
 array(
    'orderid' => "1",
    'price' => "100",
    'rate' => "1"
  ),
  array(
    'orderid' => "2",
    'price' => "200",
    'rate' => "5"
  )
);
$bonus = array();
foreach($arrays as $data){
 array_push($bonus,$data['price'] * $data['rate']);
}
print_r($bonus);
?>

You can test this code at http://www.writephponline.com/

Comments

0

Foreach is fine, but you need to add to the bonus array rather than override with the result:

$bonus = array();
 foreach($arrays as $data){
       $bonus[] = array('total' => $data['originalPrice'] * $data['rate']);
   }

This is adding arrays to the bonus array.

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.