2013-08-20 63 views
0

我有兩個陣列,我需要取決於$arr[0]["num"]從數組中取出的值,並把該值到另一個數組

$arr = array(
0 => array(
    "id" => 24, 
    "num" => 2 
), 
1 => array(
    "id" => 25, 
    "num" => 5 
) 
2 => array(
    "id" => 26, 
    "num" => 3 
) 
); 
$array = array('1','2','3','4','5','6','7','8','9','10'); 
$new = array(); 
foreach($arr as $key){ 
    for($i=0;$i<$key['num'];$i++){ 
     $new[$key['id']][$i] = $array[$i]; 
    } 
} 

的值,以提取第二數組的值是它能夠去除第二個數組的值,並將其轉移到一個新的數組?

我的循環所做的只是在每個循環之後從開始複製值。我想從第二個數組中刪除複製的值。

輸出應該是這樣的:

Array 
(
[24] => Array 
    (
     [0] => 1 
     [1] => 2 
    ) 

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

回答

1

我建議使用array_shift

$arr = array(
    array(
    "id" => 24, 
    "num" => 2 
), 
    array(
    "id" => 25, 
    "num" => 5 
), 
    array(
    "id" => 26, 
    "num" => 3 
) 
); 
$array = array('1','2','3','4','5','6','7','8','9','10'); 
$new = array(); 
foreach($arr as $key){ 
    for($i=0;$i<$key['num'];$i++){ 
     $new[$key['id']][$i] = $array[0]; // *1 
     array_shift($array); 
    } 
} 
echo '<pre>'; 
print_r($new); 

* 1,你必須改變這條線也是如此。由於array_shift移除了第一個數組項,每次迭代都應該訪問數組[0]。

輸出:

Array 
(
    [24] => Array 
     (
      [0] => 1 
      [1] => 2 
     ) 

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

    [26] => Array 
     (
      [0] => 8 
      [1] => 9 
      [2] => 10 
     ) 

) 
+0

這爲我工作。謝謝! – addykha

1

試試這個

foreach($arr as $key){ 
    for($i=0;$i<$key['num'];$i++){ 
     $new[$key['id']][$i] = $array[$i]; 

     // unset previous values, in first iteration it will remove 0, 1 
     unset($array[$i]); 
    } 
    // reset the array keys, so for loop $i will start from 0 
    $array = array_values($array); 
} 

輸出:

array (size=3) 
    24 => 
    array (size=2) 
     0 => string '1' (length=1) 
     1 => string '2' (length=1) 
    25 => 
    array (size=5) 
     0 => string '3' (length=1) 
     1 => string '4' (length=1) 
     2 => string '5' (length=1) 
     3 => string '6' (length=1) 
     4 => string '7' (length=1) 
    26 => 
    array (size=3) 
     0 => string '8' (length=1) 
     1 => string '9' (length=1) 
     2 => string '10' (length=2) 
相關問題