将1D数组转换为2D数组并加入PHP

时间:2013-12-22 09:57:58

标签: php arrays multidimensional-array array-merge

我有这个一维数组:

$ ARRAY1:

Array
(
    [coupon_code] => GTY777R
    [coupon_description] => Credito $5 USD
)

$ array2:(2D数组)

Array
(
    [0] => Array
        (
            [coupon_code] => 0000000
            [coupon_description] => Intenta de nuevo
        )

    [1] => Array
        (
            [coupon_code] => 0000000
            [coupon_description] => Intenta de nuevo
        )

)

我需要检查$ array1是否是Unidimentional数组并在加入之前转换它,例如:

if (is_1D($array1) = TRUE) {
  $array1 = convert_2D($array1);
}
$array3 = join_arrays($array1, $array2);

最终结果$ array1转换为2D并加入: $ ARRAY3

Array
(
    [0] => Array
        (
            [coupon_code] => 0000000
            [coupon_description] => Intenta de nuevo
        )

    [1] => Array
        (
            [coupon_code] => 0000000
            [coupon_description] => Intenta de nuevo
        )

    [2] => Array
        (
            [coupon_code] => GTY777R
            [coupon_description] => Credito $5 USD
        )

)

1 个答案:

答案 0 :(得分:1)

试试这个

$array1 = array(
    'coupon_code' => 'GTY777R',
    'coupon_description' => 'Credito $5 USD',
);

$array2 = array(
    array(
        'coupon_code' => '0000000',
        'coupon_description' => 'Intenta de nuevo',
    ),
    array(
        'coupon_code' => '0000000',
        'coupon_description' => 'Intenta de nuevo',
    ),
);

$result = array();

# is 1D array
if (count($array1) == count($array1, COUNT_RECURSIVE))  {
    $result[] = $array1;    
}

# join it
$result = array_merge($result, $array2);

结果

Array
(
    [0] => Array
        (
            [coupon_code] => GTY777R
            [coupon_description] => Credito $5 USD
        )

    [1] => Array
        (
            [coupon_code] => 0000000
            [coupon_description] => Intenta de nuevo
        )

    [2] => Array
        (
            [coupon_code] => 0000000
            [coupon_description] => Intenta de nuevo
        )

)