从数组中删除值并将该值放入另一个数组中

时间:2013-08-20 14:36:18

标签: php arrays

我有两个数组,我需要根据$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
    )
)

2 个答案:

答案 0 :(得分: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删除了第一个数组条目,因此每次迭代都应该访问array [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
        )

)

答案 1 :(得分: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)