簡體   English   中英

如何將兩個數組這樣組合?

[英]How to combine two arrays like this?

$ blueswards數組:

Array ( [0] => 3 [1] => 8 [2] => 1 [3] => 4 [4] => 9 ) 

$ redswards數組:

Array ( [0] => 2 [1] => 9 [2] => 3 [3] => 6 [4] => 9 ) 

我想做什么:

Array ( [0] => 3 [1] => 8 [2] => 1 [3] => 4 [4] => 9 [5] => 2 [6] => 9 [7] => 3 [8] => 6 [9] => 9 ) 

我不能用array_merge做到這一點。

編輯=對不起,我用數組合並所做的每個人現在都可以正常工作。 :[

一旦填充它們,為什么不立即循環運行它們。

$newarray=0;
$arrayCounter=0;
for (i=0; i<count($redswards)-1 ; i++){
    $newarray[$arrayCounter] = $redswards[i];
    $arrayCounter++
}
for (i=0; i<count($blueswards)-1 ; i++){
    $newarray[$arrayCounter] = $blueswards[i];
    $arrayCounter++
}

在那里...只需添加到新數組即可正確地做到這一點。 它還將計算必須循環的次數,因此您不必對其進行硬編碼。

我的意思是,這非常簡單,您可能需要更改硬編碼的i值。 但這是基本思想。

我使用array_merge()使用您的數組值。 而且,它起作用了。

<?php

$new_array[] = array(); 

$blueswards = array(3,8,4,9);
$redswards = array(2,9,3,6,9);

$new_array = array_merge($blueswards,$redswards);

print_r($new_array);

?>

輸出:

Array ( [0] => 3 [1] => 8 [2] => 4 [3] => 9 [4] => 2 [5] => 9 [6] => 3 [7] => 6 [8] => 9 ) 

使用了durbnpolsns代碼並對其進行了編輯。

$newarray=0;
for ($i=0; $i<4 ; $i++){
    $newarray[$i] = $redswards[$i];
}
$j=0;
for ($i=5; $i<8 ; $i++){
    $newarray[$i] = $blueswards[$j];
    $j++;
}

我尚未測試代碼,因此可能無法進行格式化,但是我正在手機上打字。 抱歉

暫無
暫無

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

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