yoyoma yoyoma - 1 year ago 61
PHP Question

Searching complex array for and modifying a value in php

I have a complex multi-dimensional array that looks something like

[name] => Marko Polo
[description] => New application
[number] => ABCD1234
[loans] => Array
[0] => Array
[id] => 123
[application_id] => 456
[loan_fees] => Array

[loan_parts] => Array
[0] => Array
[id] => 987
[loan_id] => 123
[product_id] => 49788
[product] => Array
[id] => 49788
[lender] => MAC


I need to create an efficient way of traversing this array and, for example having a set of rules to filter/modify the data.

For example, in the array there is
[lender] => MAC
, I want to have something like

loans.loan_parts.product.lender.MAC = 'Macquarie'

This would be in a config of sorts such that if the data array changed, it would be simply a matter of changing that dot notation to point to the new location of the

Using this, I need to filter the
and modify it to be
instead of

I know that a big no-no these days is using too many foreach loops and I've looked into Collections, but because the inner arrays are not named, I don't believe Collections is possible.

As I say, I'd like to avoid the situation of

if (is_array())


How can I execute this in the most efficient manner due to the possible large size of the array and its complexity.

Answer Source

You can use array_walk_recursive with callback that will change behavior according to key of array.

//can pass variable by reference to change array in function
function handleMAC(&$item, $key)
    if($key == 'lender'){
      $item['MAC'] = 'your value';

array_walk_recursive($array, 'handleMAC');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download