简体   繁体   English

在PHP中将一个数组分成3个不同的数组

[英]Seperate an array into 3 different arrays in PHP

I have an array like this: 我有一个像这样的数组:

array(
    '1' => 'Item 1',
    '2' => 'Item 2',
    '3' => 'Item 3',
    '4' => 'Item 4',
    '5' => 'Item 5',
    '6' => 'Item 6',
    '7' => 'Item 7',
    '8' => 'Item 8',
    '9' => 'Item 9'
);

I want to separate this into 3 arrays where keys 1,2,3 go into $array1,$array2,$array3 respectively and then keys 4,5,6 and then 7,8,9 go into $array1,$array2,$array3 respectively too. 我想将其分成3个数组,其中键1,2,3分别进入$ array1,$ array2,$ array3,然后键4,5,6然后7、8,9进入$ array1,$ array2,$ array3也是如此。

So, the final output would be: 因此,最终输出将是:

$array1 = array(
    '1' => 'Item 1',
    '2' => 'Item 4',
    '3' => 'Item 7'
);

$array2 = array(
    '1' => 'Item 2',
    '2' => 'Item 5',
    '3' => 'Item 8'
);

$array3 = array(
    '1' => 'Item 3',
    '2' => 'Item 6',
    '3' => 'Item 9'
);

Or, if they keys are preserved (and not 1,2,3 in each array as in my example) then that wouldn't matter either. 或者,如果保留了它们的键(而不是像我的示例那样在每个数组中保留1,2,3),那也将无关紧要。 Either way is fine. 两种方法都可以。

Sth like

$i=0;
foreach($array as $k=>$v) {
 ${"array".$i%3+1}[$k]=$v;
 $i++;
}
foreach($arr as $key => $value) {
    $final_arr[$key % 3][] = $value;
}
for($i = 0; $i < count($input); $i += 3) {
    ${"array".$i} = array_slice($input, 0 + $i, 3);
}

This will split your array into new array on every third element. 这会将您的数组拆分为每个第三个元素上的新数组。 You can also replace 3 with a variable to split on some other number. 您也可以将3替换为变量,以对其他数字进行分割。

Edit: oh I just noticed, you might want to offset $i to get the array names in correct order. 编辑:哦,我刚刚注意到,您可能想偏移$ i以获得正确顺序的数组名称。 Now it will be array3, array6, array9 etc 现在将是array3,array6,array9等

   Try This

          $first_arr = array();
                $second_arr = array();
                $third_arr = array();
                $first = 0;
                $second = 1;
                $third = 2;    
                foreach($array as $value)
                {
                    if ($first++ % 3 == 0)
                    $first_arr[] = $value;
                    if ($second++ % 3 == 0)
                    $second_arr[] = $value;
                    if ($third++ % 3 == 0)
                    $third_arr[] = $value;
                }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM