Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a Multidimensional Array in PHP

Tags:

arrays

php

I have an array that looks like this

$array =
    Array
    (
    [0] => Array
        (
            [Product] =>  Amazing Widget
            [Value] => 200
        )

    [1] => Array
        (
            [Product] => Super Amazing Widget
            [Value] => 400
        )

    [2] => Array
        (
            [Product] =>  Promising Widget 
            [Value] => 300
        )

    [3] => Array
        (
            [Product] => Superb Widget
            [Value] => 400
        )
    }

I want to update the array to change "Promising Widget" to 800 instead of 300.

Note that the order of this array is arbitrary, meaning that I need to update the Value Based on the "Product" name value (not on it's number in the array).

I was trying to access it via the number in the array but realized that wouldn't work for that reason and I'm not sure how to change the value of one element of a multidimensional array based on another.

Thanks for any help.

like image 880
Talon Avatar asked Apr 16 '12 18:04

Talon


3 Answers

I think you'd have to loop through them, something like:

foreach ($array as $k => $v) {
  if ($v['Product']=='Promising Widget') {
    $array[$k]['Value']=800;
  }
}
like image 100
Nick Avatar answered Nov 10 '22 08:11

Nick


I think that most universal approach is to use array_walk_recursive function like that:

array_walk_recursive($array, 'updateValue');

function updateValue(&$data, $key) {
  if($key == 'Promising Widget') {
    $data = 800;
  }
}

This way even if you will change your array later on this function still will be working fine.

like image 22
jmarceli Avatar answered Nov 10 '22 07:11

jmarceli


foreach($array as &$value){
    if($value['Product'] === 'Promising Widget'){
        $value['Value'] = 800;
        break; // Stop the loop after we've found the item
    }
}

So, you loop through the array, find value you want, then change it. The &$value is so the array is passed by reference. Meaning we can directly edit the values in the array from the loop, without having to do $array[$key]['Value'].

like image 26
Rocket Hazmat Avatar answered Nov 10 '22 07:11

Rocket Hazmat