我正在研究一个多维数组。这是我原来的数组:
$oriArr = array(
2 => array(
"A" => 'Mapping item1',
"B" => array(1 => 'product1', 2 => 'product2', 3 => 'product3'),
"C"=>array(1 => 'item1', 2 => 'item2', 3 => 'item3')
),
3 => array(
"A" => 'Mapping item2',
"B" => array(1 => 'product4', 2 => 'product5', 3 => 'product6')
"C"=>array(1 => 'item4', 2 => 'item5', 3 => 'item6')
)
);
我要做的是将原始数组转换为数组,如下所示:
$resArr = array(
"Mapping item1"=>array(
[1]=>array("product1","item1"),
[2]=>array("product2","item2"),
[3]=>array("product3","item3"),
),
"Mapping item2"=>array(
[1]=>array("product4","item4"),
[2]=>array("product5","item5"),
[3]=>array("product6","item6"),
),
);
我尝试使用array_column()但该函数只允许有2列的数组,我的原始数组有3列A,B,C。有什么建议吗?
答案 0 :(得分:1)
尝试以下功能。
function my_merge_array( $arr = [] ){
$result = [];
foreach ( $arr as $_arr ) {
$A = $_arr['A'];
foreach ($_arr['B'] as $key => $value) {
$result[$A][$key] = [ $value, $_arr['C'][$key] ];
}
}
return $result;
}
print_r( my_merge_array( $oriArr ) );
答案 1 :(得分:1)
我无法完全使用array_column来完成它,但只要产品和项目数组具有相同数量的元素,它就可以工作。
<?php
$oriArr = array(
2 => array(
'A' => 'Mapping item1',
'B' => array(1 => 'product1', 2 => 'product2', 3 => 'product3'),
'C'=>array(1 => 'item1', 2 => 'item2', 3 => 'item3')
),
3 => array(
'A' => 'Mapping item2',
'B' => array(1 => 'product4', 2 => 'product5', 3 => 'product6'),
'C'=>array(1 => 'item4', 2 => 'item5', 3 => 'item6')
)
);
$keys = array_column($oriArr,'A');
$products = array_column($oriArr,'B','A');
$items = array_column($oriArr,'C','A');
$result = [];
foreach ($keys as $k) {
$result[$k] = [];
if (isset($products[$k])) {
$i = 1;
foreach ($products[$k] as $p) {
$result[$k][] = [$products[$k][$i],$items[$k][$i]];
$i++;
}
}
}
var_dump($keys,$products,$items);
var_dump($result);