How can I find an replace an array value based on another value in the same multidimensional array

✔ Recommended Answer

A slight variant of the strategy you proposed:

<?php$data = [  [    "id" => 110,    "MainProduct" => 2,    "productName" => "Oranges",  ],  [    "id" => 111,    "MainProduct" => 110,    "productName" => "Apples",  ]];$output = [];array_walk($data, function(&$entry) use($data)  {  $mainProduct = array_search($entry['MainProduct'], $data);  $entry['productName'] = $data[$mainProduct]['productName'];});print_r($data);

The output is:

Array(    [0] => Array        (            [id] => 110            [MainProduct] => 2            [productName] => Oranges        )    [1] => Array        (            [id] => 111            [MainProduct] => 110            [productName] => Oranges        ))

Source: stackoverflow.com

Answered By: arkascha 

To find and replace an array value based on another value in the same multidimensional array in PHP, you can loop through the array using a foreach loop and check each element for the value you want to replace. When you find an element with the desired value, you can simply update its value using array assignment. Here's an example code that demonstrates how to find and replace an array value based on another value in the same multidimensional array:
php
// The multidimensional array $students = array( array('id' => 1, 'name' => 'John', 'age' => 20), array('id' => 2, 'name' => 'Jane', 'age' => 21), array('id' => 3, 'name' => 'Jim', 'age' => 22) ); // The value we want to search for $search_value = 2; // The new value we want to replace with $new_value = array('id' => 2, 'name' => 'Janette', 'age' => 21); // Loop through the array and search for the element with the matching value foreach ($students as &$student) { if ($student['id'] == $search_value) { // Replace the element with the new value $student = $new_value; break; } } // Print the updated array print_r($students);
In this example, we have a multidimensional array $students that contains information about students. We want to search for a student with an id value of 2 and replace its information with a new value. We do this by looping through the array with a foreach loop and checking each element's id value. When we find the element with an id value of 2, we replace it with the new value using array assignment. Finally, we print the updated array using the print_r() function. Note that we use the & symbol to make the $student variable a reference to the original element in the array, so that when we update it, the original array is modified.

Comments

Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755