我有这两个数组:
$arr1['product_detail'] = array(
"26" => array("Blue", "Green"),
"28" => array("S")
);
$arr2['variation'] = array(
"pupc" => array("123456", "654321"),
"pprice" => array(1, 2),
"pqty" => array(10, 11)
);
我需要构建一个包含基于位置的值的新数组,少说:
$arr3 = array(
array("Blue", "S", "123456", 1, 10),
array("Green", "S", "654321", 2, 11)
);
如果您注意到我混合了两个原始数组的所有位置。我想像是这样:
foreach ($arr2 as $key => $value) {
foreach ($value as $key1 => $value1) {
foreach ($value1 as $key2 => $value2) {
foreach ($arr1 as $key3 => $value3) {
echo $key3;
}
}
}
}
但它非常丑陋,我认为有更好的方法可以做到这一点,有什么帮助吗?
答案 0 :(得分:1)
最好使用函数
function array_addition($main_array, $new_array) {
foreach ($new_array as $aItem) {
for ($i=0;$i<=1;$i++) {
$main_array[$i][] = current($aItem) ? current($aItem) : reset($aItem);
next($aItem);
}
}
return $main_array;
}
$arr3 = array();
$arr3 = array_addition($arr3, $arr1['product_detail']);
$arr3 = array_addition($arr3, $arr2['variation']);
答案 1 :(得分:0)
$arr1['product_detail'] = array(
"26" => array("Blue", "Green"),
"28" => array("S")
);
$arr2['variation'] = array(
"pupc" => array("123456", "654321"),
"pprice" => array(1, 2),
"pqty" => array(10, 11)
);
function convert_array_index_name_to_number($arr)
{
$temp_ar = array();
foreach($arr as $key=>$val)
{
if(is_array($val))
{
$val = convert_array_index_name_to_number($val);
}
$temp_ar[] = $val;
}
return $temp_ar;
}
$arr1 = convert_array_index_name_to_number($arr1);
$arr2 = convert_array_index_name_to_number($arr2);
$arr3 = array();
for($i=0; $i<$count_of_variations; $i++)
{
$temp_arr = array();
$temp_arr[] = $arr1[0][0][$i];
$temp_arr[] = $arr1[0][1][0];
foreach($arr2[0] as $key => $value)
{
$temp_arr[] = $value[$i];
}
$arr3[] = $temp_arr;
}
结果
Array
(
[0] => Array
(
[0] => Blue
[1] => S
[2] => 123456
[3] => 1
[4] => 10
)
[1] => Array
(
[0] => Green
[1] => S
[2] => 654321
[3] => 2
[4] => 11
)
)