phparrayslaravelmultidimensional-arrayarray-sum

how to add multidimensional array values ​whose values ​are from different arrays


I have been fighting with this all day and would like another set of eyes to maybe give me some insight. I'm not sure I am even approaching this the correct way. I have two arrays, namely a multidimensional array and a single array, I am trying to add up the contents of a multidimensional array whose values ​​are taken from a single array, where the contents of the multidimensional array are the same as the array keys of a single array. I'm building an app with Laravel.

$multidimensionArray = array:6 [▼
  "A2" => array:3 [▼
    0 => "A1"
    1 => "A2"
    2 => "A3"
  ]
  "A1" => array:4 [▼
    0 => "A1"
    1 => "A6"
    2 => "A5"
    3 => "A2"
  ]
  "A6" => array:1 [▼
    0 => "A3"
  ]
  "A3" => array:2 [▼
    0 => "A3"
    1 => "A2"
  ]
  "A5" => array:1 [▼
    0 => "A4"
  ]
  "A4" => array:2 [▼
    0 => "A4"
    1 => "A3"
  ]
]

$singeArray = array:6 [▼
  "A1" => 675.58333333333
  "A2" => 1786.75
  "A3" => 2897.9166666667
  "A4" => 4009.0833333333
  "A5" => 5120.25
  "A6" => 6231.4166666667
]

how to add the value in $multidimensionalArray according to the key whose value is taken from $singleArray, then divided by the number of keys in $multidimensionalArray, for example: in key "A2" in multidimensionalArray has values ​​A1,A2,A3 and in singleArray the values ​​of A1,A2,A3 are 675.58333333333, 1786.75, 2897.9166666667, how to add them then divide by 3(according to the number of values ​​in A2).

I hope the result is like this

$result = array(
"A2" => 1786.75
"A1" => 3453.5
...etc

)

Solution

  • I would use a foreach and array_filter.

    Since you want average of the values it can be done with array_sum.

    This should work

    $results = [];
    foreach ($multidimensionArray as $key => $valueArr) {
        ## filter out all values of interest from $singleArray
        $filteredValues = array_filter($singeArray, function ($value, $identifier) use ($valueArr) {
            return in_array($identifier, $valueArr);
        }, ARRAY_FILTER_USE_BOTH);
        ## Here we get the average
        $results[$key] = array_sum($filteredValues) / count($filteredValues);
    }
    print_r($results);
    

    Working sandbox link