简体   繁体   English

PHP数组合并/两个数组的映射

[英]PHP array merge / map of two arrays

I have two arrays, one that contains all options, and a second one that contains the default values. 我有两个数组,一个包含所有选项,另一个包含默认值。

The options arrays looks like this: 选项数组如下所示:

$options = array(
   "SeriesA" => array(
       "A1" => array(
          "text" => "A1",
          "value" => "A-001"
        ),
       "A2" => array(
          "text" => "A2",
          "value" => "A-002"
        )
    ),
  "SeriesB" => array(
       "B1" => array(
          "text" => "B2",
          "value" => "B-001"
        ),
       "B2" => array(
          "text" => "B2",
          "value" => "B-002"
        )
    ),
);

And I have another array that contains default value, and it looks like this 我还有另一个包含默认值的数组,它看起来像这样

$defaults= array(
   "SeriesA" => "A-002",
   "SeriesB" => "B-001",
);

What I would like to end up with is one array that contains all info, is there a way that I can map both arrays and get one array that will look like this: 我想最终得到的是一个包含所有信息的数组,有没有一种方法可以映射两个数组并获得一个看起来像这样的数组:

$options = array(
   "SeriesA" => array(
       "A1" => array(
          "text" => "A1",
          "value" => "A-001",
          "default" => false
        ),
       "A2" => array(
          "text" => "A2",
          "value" => "A-002",
          "default" => true
        )
    ),
  "SeriesB" => array(
       "B1" => array(
          "text" => "B2",
          "value" => "B-001",
          "default" => true
        ),
       "B2" => array(
          "text" => "B2",
          "value" => "B-002",
          "default" => false
        )
    ),
);

Here is two ways to do it: 这是两种方法:

Make a function, which accepts two args and check value in a loop with defaults, add defaults, and returns new array, or edit array, passing it by reference: 创建一个函数,该函数接受两个args并在具有默认值的循环中检查值,添加默认值,并返回新数组或编辑数组,并按引用传递它:

function awesomeName(&$options, $defaults) {
    foreach ($options as $k => &$values) {
        foreach ($values as &$AsAndBs) {
            $AsAndBs['default'] = $AsAndBs['value'] == $defaults[$k];
        }
    }
}

Using array_walk() function with anonymous function: 使用array_walk()函数和匿名函数:

array_walk($options, function (&$v, $k) use ($defaults) {
    $series = $k;
    foreach ($v as &$series_contents) {
        $series_contents['default'] = $series_contents['value'] == $defaults[$series];
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM