簡體   English   中英

將一維數組轉換為二維數組並加入PHP

[英]Convert 1D Array to 2D Array and Join PHP

我有這個一維數組:

$ array1:

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

$ array2:(二維數組)

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

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

)

我需要檢查$ array1是否是一個Unidimentional Array,並在加入之前進行轉換,例如:

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
        )

)

嘗試這個

$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
        )

)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM