Reputation: 43
I have a a Multidimensional array with a lot of content that includes a label for each piece of content, and I have a separate array with a Key that is the label being searched for and the value that is to replace it.
I want to use the second array to replace nested label values in the first array. The function should find the first Array's label value based on the key of the second array, and replace it using that Key's value.
For Example the content Array:
Array
(
[Name] => Array
(
[0] => Array
(
[label] => Name
[content] => Important Paper
)
[1] => Array
(
[label] => Item Type
[content] => Document
)
[2] => Array
(
[label] => Author
[content] => Bob Jones
)
)
[date] => Array
(
[0] => Array
(
[label] => Date
[content] => 2009
)
)
)
And an example of the array looking to replace the value
Array
(
[Name] => Record
[Author] => Researcher
[Date] => Year
)
The output I would want from this function would resemble
Array
(
[Name] => Array
(
[0] => Array
(
[label] => Record
[content] => Important Paper
)
[1] => Array
(
[label] => Item Type
[content] => Document
)
[2] => Array
(
[label] => Researcher
[content] => Bob Jones
)
)
[date] => Array
(
[0] => Array
(
[label] => Year
[content] => 2009
)
)
)
Right now I am attempting to get the results by using a series of forloops and if statements. I don't actually know the depth that the [label] key will be found at, and it should only update content with the key value [label].
Any insight on a way to do this more efficiently would be great. I've also been looking at all of the different php array functions and trying to find the best combinations.
Upvotes: 1
Views: 863
Reputation: 3815
you can use: array_walk_recursive
from: php.net
$orig = array('Name' => [['label' => 'Name', 'content' => 'Important Paper'],
['label' => 'Item Type', 'content' => 'Document'],
['label' => 'Author', 'content' => 'Bob Jones']],
'date' => [[['label' => 'Date', 'content' => '2009']]]);
// notice the `&` symbol, this allows us to change the original array on the fly
function replaceIt(&$item){
$replaceArray = ['Name' => 'Record',
'Author' => 'Researcher',
'Date' => 'Year'];
foreach ($replaceArray as $key => $value) {
if($key == $item){ $item = $value; }
}
}
array_walk_recursive($orig, 'replaceIt');
print('<pre>');
print_r($orig);
print('</pre>');
Upvotes: 1