Jump to content

looping and updating a multidimensional array


isedeasy

Recommended Posts

I have an array which I contains multiple arrays, I would like to loop through and run a function on a certain key  within the array

 

I have the following code which works but I was wondering if there was a better method?

 

$i = 0;
foreach($Items as $Item) {
$Items[$i]['key'] = custom_function($Item['key']);
$i++;
}

 

The array $Items structure is as follows

 

array (
[0] => array (
[key] => 'blah'
)
[1] => array (
[key] => 'blah'
)
[2] => array (
[key] => 'blah'
)
)

Or just use the array_map() function conveniently built intp PHP

 

$Items = array_map('custom_function', $Items);

 

Of course your function would have to expect the inner array object and return the same.

 

But, I have to ask - why do you have a two dimensional array if the secondary array only consists of a single element?

thanks AbraCadaver, that was the first method I tried but I did not have the $Item in the for loop as a reference which is why it did not work :)

 

mjdamato, the array I posted was just an example to save space, that is why secondary array only has one element.

 

I had a quick look at array_map but looking at your example I can't see where you tell it what element to effect?

 

Thanks for help

  Quote

I had a quick look at array_map but looking at your example I can't see where you tell it what element to effect?

 

You don't specify any field in array_map(). array_map() takes two parameters: a custom functino that you provide and an array. The function is what determines what happens to the values. So, the function would receive one subarray element and should return a sub-array element (with whatver values you want it to have). You don't show what the function 'custom_function' is supposed to do (poor name of a function if I ever saw one). But, let's say the function is supposed to do somethign simple such as change the value of the 'key' element to lower case. Then you would simply write the function like this

 

functin custom_function($sub_array)
{
    $sub_array['key'] = strtolower($sub_array['key']);
    return $sub_array;
}

 

Then if ther are any other elements in teh sub array they will remain unchanged. Only the 'key' element will be changed.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.