我试图将数组#2中的2个字段连接到数组#1
数组#1
Array ( [0] => Array ( [id] => 1 [position] => top_banner_1 [name] => Top Banner 1 [order] => 1 ) [1] => Array ( [id] => 2 [position] => left_banner_1 [name] => Left Banner 1 [order] => 2 ) )
数组#2
Array ( [status] => 0 [countries] => [module_status] => 1 [top_banner_1_status] => 1 [top_banner_1_display] => 0 [left_banner_1_status] => 1 [left_banner_1_display] => 0 [left_banner_2_status] => 1 [left_banner_2_display] => 0 [left_banner_3_status] => 1 [left_banner_3_display] => 0 [left_banner_4_status] => [left_banner_4_display] => 0 [left_banner_5_status] => [left_banner_5_display] => 0 [center_banner_1_status] => [center_banner_1_display] => 0 [center_banner_2_status] => [center_banner_2_display] => 0 [right_banner_1_status] => [right_banner_1_display] => 0 [right_banner_2_status] => [right_banner_2_display] => 0 [right_banner_3_status] => [right_banner_3_display] => 0 [right_banner_4_status] => [right_banner_4_display] => 0 [right_banner_5_status] => [right_banner_5_display] => 0 [bottom_banner_1_status] => [bottom_banner_1_display] => 0 )
我想要实现的目标是:
Array ( [0] => Array ( [id] => 1 [position] => top_banner_1 [name] => Top Banner 1 [order] => 1 [top_banner_1_status] => 1 [top_banner_1_display] => 0 ) )
这两个数组都来自数据库。阵列#1中有13个区域,所以到目前为止我所做的一切都是使用foreach循环,因为阵列#2数据是从理想情况下无法编辑的函数中获取的。
我已经尝试了很多array_*
功能,但我的速度不是很快。
答案 0 :(得分:2)
假设有以下推理:
Array
(
[0] => Array
(
[id] => 1
[position] => top_banner_1
[name] => Top Banner 1
[order] => 1
[top_banner_1_status] => 1 // Added because of key is [position]_status.
[top_banner_1_display] => 0 // Added because of key is [position]_display.
)
)
我愿意:
<?php
$array1 = // Array #1 from question.
$array2 = // Array #2 from question.
foreach ($array1 as $key => $item) {
$position = $item['position'];
$keySuffixes = array('_status', '_display');
foreach ($keySuffixes as $suff) {
if (array_key_exists($position . $suff, $array2)) {
$array1[$key][$position . $suff] = $array2[$position . $suff];
}
}
}
&GT;
不太优雅,我知道:(
答案 1 :(得分:0)
诀窍是根据ID构造一个密钥以从$ arr2获取数据。
foreach($arr1 as $key=>$val){
$id = $val['id'];
$tb_status_key = "top_banner_{$id}_status";
$tb_display_key = "top_banner_{$id}_display";
$arr1[$key][$tb_status_key] = $arr2[$tb_status_key];
$arr1[$key][$tb_display_key] = $arr2[$tb_display_key];
}
答案 2 :(得分:0)
Array#2的结构对于此任务并不十分适用。如果你有可能,你应该把它改成这样的东西:
Array
(
[top_banner_1] => Array (
[status] => 1
[display] => 0
)
[left_banner_1] => Array (
[status] => 1
[display] => 0
)
)
//and so on
但是如果 不可能,这应该有效:
foreach($array1 as &$info) {
$status = $info['position'] . '_status';
$display = $info['position'] . '_display';
$info[$status] = $array2[$status];
$info[$display] = $array2[$display];
}
否则,这似乎是一种更优雅的方式:
foreach($array1 as &$info) {
$info['status'] = $array2[$info['position']]['status'];
$info['display'] = $array2[$info['position']]['display'];
}