递归地将一个数组替换为具有另一个数组的特定键

时间:2018-08-31 14:17:00

标签: php

我有一个数组,其中键type == 'foo'处的所有数组都必须替换为自定义数组。 基本上,我需要找到一个特定的数组,然后将其替换为其他数组。

这里的问题是您可以轻松替换一个数组,但是当您插入多个数组时,您需要移动键,因此下一个数组type == 'foo'不会被替换

任何帮助将不胜感激。

这就是我所拥有的:

$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'
        )
      )
   ),
);

我有一个应该替换type == 'foo'

处的任何数组的数组
$array_foo = array(
  array(
    'type' => 'custom'
  ),
  array(
    'type' => 'custom_2'
  ),
  array(
    'type' => 'anything'
  ),
);

这是所需的输出:

$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'
        ),
      )
   ),
);

谢谢。

2 个答案:

答案 0 :(得分:1)

这是将 2个嵌套的foreach循环array_merge()临时数组一起使用的一种方法:

// 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;
}

并检查输出:

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

另请参阅Passing by Reference

答案 1 :(得分:-1)

根据上一篇文章,更改代码的方式类似于以下代码:

$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");

$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);

因此,通过您的方法而不是使用数字或索引,我认为您可以摆脱写下foo的麻烦,而使替换工作正常进行。

您可能要研究的另一件事是数组合并递归,可以在http://php.net/array_merge_recursive

中找到

您在此处说明的问题与这篇文章类似:PHP Array Merge two Arrays on same key

希望对您有帮助。

相关问题