我有两个数组,一个包含所有选项,另一个包含默认值。
选项数组如下所示:
$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"
)
),
);
我有另一个包含默认值的数组,它看起来像这个
$defaults= array(
"SeriesA" => "A-002",
"SeriesB" => "B-001",
);
我想最终得到的是一个包含所有信息的数组, 有没有办法可以映射两个数组并获得一个如下所示的数组:
$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
)
),
);
答案 0 :(得分:1)
以下是两种方法:
创建一个函数,它接受两个args并在一个循环中检查默认值,添加默认值,并返回新数组,或编辑数组,通过引用传递它:
function awesomeName(&$options, $defaults) {
foreach ($options as $k => &$values) {
foreach ($values as &$AsAndBs) {
$AsAndBs['default'] = $AsAndBs['value'] == $defaults[$k];
}
}
}
使用带有匿名函数的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];
}
});