Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive replace one array with specific key with another arrays

Tags:

php

I have an array where all arrays where key type == 'foo' must be replaced by a custom arrays. Basically I need to find a specific array and then replace it with other arrays.

The issue here you can easily replace one array but when you insert numbers of arrays you are shifting keys so the next array type == 'foo' will not be replaced

Any help would be appreciated.

Here's what I have:

$array = array(
   array(
     'options' => array(
        array(
          'type' => 'foo'
        ),
        array(
          'type' => 'foo'
        ),
        array(
          'type' => 'bar'
        )
      )
   ),
   array(
     'options' => array(
        array(
          'type' => 'bar'
        ),
        array(
          'type' => 'bar'
        ),
        array(
          'type' => 'foo'
        )
      )
   ),
);

And I have an array which should replace any array where type == 'foo'

$array_foo = array(
  array(
    'type' => 'custom'
  ),
  array(
    'type' => 'custom_2'
  ),
  array(
    'type' => 'anything'
  ),
);

Here is the desired output:

$array = array(
   array(
     'options' => array(
        array(
          'type' => 'custom'
        ),
        array(
          'type' => 'custom_2'
        ),
        array(
          'type' => 'anything'
        ),
        array(
          'type' => 'custom'
        ),
        array(
          'type' => 'custom_2'
        ),
        array(
          'type' => 'anything'
        ),
        array(
          'type' => 'bar'
        )
      )
   ),
   array(
     'options' => array(
        array(
          'type' => 'bar'
        ),
        array(
          'type' => 'bar'
        ),
        array(
          'type' => 'custom'
        ),
        array(
          'type' => 'custom_2'
        ),
        array(
          'type' => 'anything'
        ),
      )
   ),
);

Thank you.

like image 448
Artem Avatar asked Feb 15 '26 11:02

Artem


1 Answers

Here's a way using 2 nested foreach loops and array_merge() with a temporary array:

// Pass the array by reference
foreach ($array as &$sub) {
    // Temporary array
    $new_options = [];
    // Loop through options
    foreach ($sub['options'] as $opt) {

        // if type foo: replace by $array_foo items
        if ($opt['type'] == 'foo') {
            $new_options = array_merge($new_options, $array_foo);

            // else, keep original item
        } else {
            $new_options[] = $opt;
        }
    }

    // replace the options
    $sub['options'] = $new_options;
}

And check the output:

echo '<pre>' . print_r($array, true) . '</pre>';

See also Passing by Reference

like image 92
AymDev Avatar answered Feb 17 '26 02:02

AymDev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!