John Davidson

php - Add new associative element to each row of a 2d array

0 comments
Message:


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


$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 the browser, there is a warning message:



Uncaught TypeError: Illegal offset type in line $data[$value]['average'] = ($a * 0.5) + ($b * 0.6);



The result that I want 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],
];


My Answer:
['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 30],
['name' => 'Bob', 'age' => 35]
];

I want to add a new key-value pair to each row, like this:

$data = [
['name' => 'John', 'age' => 25, 'city' => 'New York'],
['name' => 'Jane', 'age' => 30, 'city' => 'Los Angeles'],
['name' => 'Bob', 'age' => 35, 'city' => 'Chicago']
];

To achieve this, you can use a foreach loop to iterate over each row of the 2D array and add the new key-value pair to each row. Here's an example code snippet to do this:

php
$data = [
['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 30],
['name' => 'Bob', 'age' => 35]
];

$newKey = 'city';
$newValue = ['New York', 'Los Angeles', 'Chicago'];

foreach ($data as $key => $row) {
$data[$key][$newKey] = $newValue[$key];
}

print_r($data);


This code snippet will add the 'city' key with corresponding values from the `$newValue` array to each row of the `$data` array.

Rate this post

3 of 5 based on 1152 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us