'how to add new key and value in multidimensional array?

I want to add key and value array multidimensional . I have 1 array multidimensional, like this :

<?php
$data = [
    ["name" => "albert","id"=>2101001,"value1"=>87 ,"value2"=>63,],
    ["name" => "andrew","id"=>2101002,"value1"=>76 ,"value2"=>79,],
   ];

   foreach ($data as $value) {
       $a = $value['value1'];
       $b = $value['value2'];
       $data[$value]['average'] = ($a * 0.5) + ($b * 0.6) ;
       echo $value['average'];
   }
?>

when i run it in browser , there is a warning message Uncaught TypeError: Illegal offset type in line $data[$value]['average'] = ($a * 0.5) + ($b * 0.6) ; result iwant is like this :

$dataresult = [
    ["name" => "albert","id"=>2101001,"value1"=>87 ,"value2"=>63, "average"=> 81.3 ],
    ["name" => "andrew","id"=>2101002,"value1"=>76 ,"value2"=>79, "average"=> 85.4],
   ];

i hope you can help me , thank you



Solution 1:[1]

Need to get the $key reference at the foreach loop to help index into the data:

$data = [
    ["name" => "albert","id"=>2101001,"value1"=>87 ,"value2"=>63,],
    ["name" => "andrew","id"=>2101002,"value1"=>76 ,"value2"=>79,],
   ];

   foreach ($data as $key => $value) {
       $a = $value['value1'];
       $b = $value['value2'];
       $data[$key]['average'] = ($a * 0.5) + ($b * 0.6) ;
       echo $value['average'];
   }

var_dump($data);

output:

array(2) {
  [0]=>
  array(5) {
    ["name"]=>
    string(6) "albert"
    ["id"]=>
    int(2101001)
    ["value1"]=>
    int(87)
    ["value2"]=>
    int(63)
    ["average"]=>
    float(81.3)
  }
  [1]=>
  array(5) {
    ["name"]=>
    string(6) "andrew"
    ["id"]=>
    int(2101002)
    ["value1"]=>
    int(76)
    ["value2"]=>
    int(79)
    ["average"]=>
    float(85.4)
  }
}

PHP fiddle example here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paul T.