2

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

2
  • Can you explain better what calculations you want to do from A and B? Commented Dec 15, 2019 at 20:58
  • multiplication, division and addition. like the formula above Commented Dec 16, 2019 at 1:40

1 Answer 1

1

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

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

3 Comments

I can't use it, because I have a lot of data from Array A. So it's difficult if I have to write one at a time for each element of array A. I only give an example for array A, because if not it will take too long if I have to write it. Can you provide a more dynamic answer for array A?
@RizalTerrisElvalino, then why you didn't provide this note in your answer? Updated
ok thanks, let me check it out first. if it's working fine , i'll accept this answer

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.