Rizal Terris Elvalino
Rizal Terris Elvalino

Reputation: 77

Calculation from Dynamic array and object

I have an array of objects A and an array B

An array of objects A looks like this

array(2) {
  [0]=>
  object(stdClass)#30 (5) {
    ["kriteria_kode"]=>
    string(2) "C1"
    ["kriteria_bobot"]=>
    string(2) "70"
  }
  [1]=>
  object(stdClass)#31 (5) {
    ["kriteria_kode"]=>
    string(2) "C2"
    ["kriteria_bobot"]=>
    string(2) "30"
  }
}

and an array B looks like this

array(5) {
  [0]=>
  array(2) {
    [0]=>
    int(5)
    [1]=>
    float(4.7)
  }
  [1]=>
  array(2) {
    [0]=>
    float(4.4)
    [1]=>
    float(4.6)
  }
  [2]=>
  array(2) {
    [0]=>
    float(4.8)
    [1]=>
    float(4.4)
  }
  [3]=>
  array(2) {
    [0]=>
    float(4.7)
    [1]=>
    float(4.65)
  }
  [4]=>
  array(2) {
    [0]=>
    float(4.3)
    [1]=>
    float(4.8)
  }
}

I want to produce calculation results from both arrays(A and B) using formula below:

Array C[0] = ((Array B[0][0]*Array A[0]->kriteria_bobot)/100) +  ((Array B[0][1]*Array A[1]->kriteria_bobot)/100) 
Array C[0] = ((5*70)/100) + ((4.7*30)/100))
Array C[0] = 3.5 + 1.41
Array C[0] = 4.91

The final results should be like

C[0] = 4.91
C[1] = 4.46
C[2] = 4.68
C[3] = 4.685
C[4] = 4.45

I confused for getting output by doing calculations from objects and arrays

Upvotes: 2

Views: 65

Answers (1)

Aksen P
Aksen P

Reputation: 4599

You can use a simple foreach loop like this one:

foreach($B as $pair){
    $C[] = ($pair[0]*$A[0]->kriteria_bobot)/100 + ($pair[1]*$A[1]->kriteria_bobot)/100;
}

Outputs:

Array
(
    [0] => 4.91
    [1] => 4.46
    [2] => 4.68
    [3] => 4.685
    [4] => 4.45
)

Demo

You've asked to make a dynamic stuff for array A. I'd like to note you, that the length of array A must be the same as the length of 1 sub-array from array B:

foreach($B as $pair){
    $tmp = 0;
    foreach($A as $ind=>$ob){
        $tmp += ($pair[$ind]*$ob->kriteria_bobot)/100;
    }
    $C[] = $tmp;
}

Demo2

Upvotes: 1

Related Questions