1

我有这两个数组:

$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;
            }
        }
    }
}

但这很丑陋,我认为有更好的方法来做到这一点,有什么帮助吗?

4

2 回答 2

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']);
于 2013-09-24T19:25:20.477 回答
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
        )

)
于 2013-09-24T20:55:43.453 回答