将数组拆分为N数组- PHP。

时间:2022-06-27 02:42:14

I have an array of 18 values:

我有一个18个值的数组:

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r');

I want to split this array into 12 different arrays so it should look like this:

我想把这个数组分成12个不同的数组所以它应该是这样的

array(
    0 => array('a', 'b'),
    1 => array('c', 'd'),
    2 => array('e', 'f'),
    3 => array('g', 'h'),
    4 => array('i', 'j'),
    5 => array('k', 'l'),
    6 => array('m'),
    7 => array('n'),
    8 => array('o'),
    9 => array('p'),
   10 => array('q'),
   11 => array('r')
)

My function doesn't seem to work

我的功能好像不起作用。

function array_split($array, $parts){
    return array_chunk($array, ceil(count($array) / $parts));
}

$result = array_split($array, 12);

because I get 9 different arrays instead of 12. It would return

因为我得到9个不同的数组而不是12个。它将返回

array(
    0 => array('a', 'b'),
    1 => array('c', 'd'),
    2 => array('e', 'f'),
    3 => array('g', 'h'),
    4 => array('i', 'j'),
    5 => array('k', 'l'),
    6 => array('m', 'n'),
    7 => array('o', 'p'),
    8 => array('q', 'r')
)

How would I go about doing this? Thanks.

我该怎么做呢?谢谢。

9 个解决方案

#1


29  

This simple function would work for you:

这个简单的函数可以为你工作:

Usage

使用

$array = range("a", "r"); // same as your array
print_r(alternate_chunck($array,12));

Output

输出

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
            [1] => f
        )

    [3] => Array
        (
            [0] => g
            [1] => h
        )

    [4] => Array
        (
            [0] => i
            [1] => j
        )

    [5] => Array
        (
            [0] => k
            [1] => l
        )

    [6] => Array
        (
            [0] => m
        )

    [7] => Array
        (
            [0] => n
        )

    [8] => Array
        (
            [0] => o
        )

    [9] => Array
        (
            [0] => p
        )

    [10] => Array
        (
            [0] => q
        )

    [11] => Array
        (
            [0] => r
        )

)

Update The above might not be useful for most cases ... here is another type of chunk

更新上面的内容可能对大多数情况不太有用……这是另一种类型的数据块。

$array = range("a", "r"); // same as your array
print_r(fill_chunck($array, 5));

Output

输出

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] => c
            [3] => d
        )

    [1] => Array
        (
            [0] => e
            [1] => f
            [2] => g
            [3] => h
        )

    [2] => Array
        (
            [0] => i
            [1] => j
            [2] => k
            [3] => l
        )

    [3] => Array
        (
            [0] => m
            [1] => n
            [2] => o
            [3] => p
        )

    [4] => Array
        (
            [0] => q
            [1] => r
        )

)

This would make sure the group at no time is more that 5 elements where the other one has no limitation

这将确保组在任何时候都是5个元素,其中另一个没有限制。

Function Used

函数使用

function alternate_chunck($array, $parts) {
    $t = 0;
    $result = array();
    $max = ceil(count($array) / $parts);
    foreach(array_chunk($array, $max) as $v) {
        if ($t < $parts) {
            $result[] = $v;
        } else {
            foreach($v as $d) {
                $result[] = array($d);
            }
        }
        $t += count($v);
    }
    return $result;
}


function fill_chunck($array, $parts) {
    $t = 0;
    $result = array_fill(0, $parts - 1, array());
    $max = ceil(count($array) / $parts);
    foreach($array as $v) {
        count($result[$t]) >= $max and $t ++;
        $result[$t][] = $v;
    }
    return $result;
}

#2


5  

You said:

你说:

I have 13 categories in the DB that I want to group them into 12 arrays. If there are more than 12 categories, which there are, then insert the remaining values starting from the first array.

我在DB中有13个类别,我想把它们组合成12个数组。如果有超过12个类别,其中有,那么从第一个数组开始插入剩余的值。

This works, but what should be the output if you have more elements in the input array?

这是可行的,但是如果在输入数组中有更多的元素,那么输出应该是什么呢?

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm');

function s($array, $am) {
    $r = array();
    $d = count($array) - $am+1;
    foreach ($array as $k => $v) {
        if ($k < $d) {
            if (!isset($r[0])) {
                $r[0] = array($v);
            } else {
                $r[0] = array_merge($r[0], array($v));
            }
        } else {
            $r[] = array($v);
        }
    }

    return $r;
}

will return

将返回

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
        )

    [2] => Array
        (
            [0] => d
        )

    [3] => Array
        (
            [0] => e
        )

    [4] => Array
        (
            [0] => f
        )

    [5] => Array
        (
            [0] => g
        )

    [6] => Array
        (
            [0] => h
        )

    [7] => Array
        (
            [0] => i
        )

    [8] => Array
        (
            [0] => j
        )

    [9] => Array
        (
            [0] => k
        )

    [10] => Array
        (
            [0] => l
        )

    [11] => Array
        (
            [0] => m
        )

)

#3


2  

You can use array_chunk and array_merge for this problem:

您可以使用array_chunk和array_merge来解决这个问题:

<?php 

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r');
$chunked_arr = array_chunk($array,12);
$j = 0;
for($i = 0; $i < count($chunked_arr[0]); $i++){
    if(!($i % 2 == 0)){
        $first_combined[$j][$i % 2] = $chunked_arr[0][$i];
        $j++;
    } else {
    $first_combined[$j][$i % 2] = $chunked_arr[0][$i];
    }
}

$merged_array = array_merge($first_combined, $chunked_arr[1]); 

echo '<pre>';
print_r($merged_array);
 ?>

And You will get the result like this:

你会得到这样的结果:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
            [1] => f
        )

    [3] => Array
        (
            [0] => g
            [1] => h
        )

    [4] => Array
        (
            [0] => i
            [1] => j
        )

    [5] => Array
        (
            [0] => k
            [1] => l
        )

    [6] => m
    [7] => n
    [8] => o
    [9] => p
    [10] => q
    [11] => r
)

This is what exactly you want.

这正是你想要的。

Live Demo Here>>

现场演示这里> >

#4


1  

ceil(count($array) / $parts) would give 2, so each array is being filled up with 2 items until you dont have 2 items left. hence the last one has 1 item. this will work when you have a huge amount of data in the array, but not so much when you have a small amount of data.

ceil(count($array) / $parts)会给出2,所以每个数组都被填充了2个条目,直到你没有剩下2个条目。因此最后一个有1个项。当数组中有大量数据时,这将起作用,但当您有少量数据时,就不会这么做了。

#5


1  

What you are describing is not what array_chunk is made for. You should use array_slice() and calculate yourself which parts of the array you want to end up as new arrays. (and use a for loop to iterate over your original array)

你所描述的并不是array_chunk所做的。您应该使用array_slice(),并计算自己希望作为新数组结束的数组的哪些部分。(并使用for循环遍历原始数组)

Update:

更新:

Some calculations that could help you:

一些计算可以帮助你:

minimum_fill = floor(array_length / nr_buckets)
bigger_buckets_amount = array_length - (minimum_fill / nr_buckets)

Algorithm to fill buckets: Loop over the array, fill the first bigger_buckets_amount amount of buckets with (minimum_fill + 1), fill the rest of the buckets with minimum_fill

算法来填充bucket:循环遍历数组,用(minimum_fill + 1)填充第一个较大的桶数,用minimum_fill填充其余的桶。

#6


1  

Compile that and see if it does for you:

编译它,看看它是否适合你:

<?php

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm');

$sliceA = 0;
$sliceB = 2;

$final = array(array_slice($array, $sliceA, $sliceB));


for ($i=$sliceB; $i<sizeof($array); $i++)
{
    $final[$sliceB-1] = array($array[$i]);
    $sliceB++;
}

var_dump($final);

#7


1  

<?php
$array = range('a','r');
$length = array(2=>6,1=>6); // 2=>6 means -- first six elements of new array will have 2 elements each and then, 1=>6 means -- next six elements of new array will have 1 element each
$target = array(); // or use []  in PHP 5.4
foreach($length as $i=>$times) {
    while($times>0){
        $target[] = array_splice($array, 0, $i);
        $times--;
    }
}
print_r($target);
?>

#8


1  

This will do it for you!
Here, I used my function smallify() to break an array of 15 elements into 3 arrays of 5 elements each.

这是为你做的!在这里,我使用了我的函数smallify()将15个元素的数组分解成3个数组,每个数组包含5个元素。

<?php

$bigArray = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);

echo ("<pre>");
print_r (smallify($bigArray, 3));
echo ("<pre/>");


function smallify($arr, $numberOfSlices){

  $sliceLength = sizeof($arr) /$numberOfSlices;
  for($i=1; $i<=$numberOfSlices; $i++){

       $arr1 = array_chunk($arr, $sliceLength*$i);
       return $arr1;
       unset($arr1);

   }

}
?>

Result

结果

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

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

[2] => Array
    (
        [0] => 11
        [1] => 12
        [2] => 13
        [3] => 14
        [4] => 15
    )

)

#9


0  

I believe the problem is that you are using a size of 2 when using array_chunk. This ensures that each new array created has two items in it if possible. This causes the function to run out of variables to put into the new arrays by the time you get to 10. You can find the manual on the function here http://php.net/manual/en/function.array-chunk.php Hope this helps

我认为问题是使用array_chunk时使用的是2的大小。这确保了每个新创建的数组都有两个项目。这将导致函数在您到达10时耗尽变量,并将其放入新的数组中。您可以在这里找到这个函数的手册http://php.net/manual/en/function.array-chunk.php希望这能有所帮助。

#1


29  

This simple function would work for you:

这个简单的函数可以为你工作:

Usage

使用

$array = range("a", "r"); // same as your array
print_r(alternate_chunck($array,12));

Output

输出

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
            [1] => f
        )

    [3] => Array
        (
            [0] => g
            [1] => h
        )

    [4] => Array
        (
            [0] => i
            [1] => j
        )

    [5] => Array
        (
            [0] => k
            [1] => l
        )

    [6] => Array
        (
            [0] => m
        )

    [7] => Array
        (
            [0] => n
        )

    [8] => Array
        (
            [0] => o
        )

    [9] => Array
        (
            [0] => p
        )

    [10] => Array
        (
            [0] => q
        )

    [11] => Array
        (
            [0] => r
        )

)

Update The above might not be useful for most cases ... here is another type of chunk

更新上面的内容可能对大多数情况不太有用……这是另一种类型的数据块。

$array = range("a", "r"); // same as your array
print_r(fill_chunck($array, 5));

Output

输出

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] => c
            [3] => d
        )

    [1] => Array
        (
            [0] => e
            [1] => f
            [2] => g
            [3] => h
        )

    [2] => Array
        (
            [0] => i
            [1] => j
            [2] => k
            [3] => l
        )

    [3] => Array
        (
            [0] => m
            [1] => n
            [2] => o
            [3] => p
        )

    [4] => Array
        (
            [0] => q
            [1] => r
        )

)

This would make sure the group at no time is more that 5 elements where the other one has no limitation

这将确保组在任何时候都是5个元素,其中另一个没有限制。

Function Used

函数使用

function alternate_chunck($array, $parts) {
    $t = 0;
    $result = array();
    $max = ceil(count($array) / $parts);
    foreach(array_chunk($array, $max) as $v) {
        if ($t < $parts) {
            $result[] = $v;
        } else {
            foreach($v as $d) {
                $result[] = array($d);
            }
        }
        $t += count($v);
    }
    return $result;
}


function fill_chunck($array, $parts) {
    $t = 0;
    $result = array_fill(0, $parts - 1, array());
    $max = ceil(count($array) / $parts);
    foreach($array as $v) {
        count($result[$t]) >= $max and $t ++;
        $result[$t][] = $v;
    }
    return $result;
}

#2


5  

You said:

你说:

I have 13 categories in the DB that I want to group them into 12 arrays. If there are more than 12 categories, which there are, then insert the remaining values starting from the first array.

我在DB中有13个类别,我想把它们组合成12个数组。如果有超过12个类别,其中有,那么从第一个数组开始插入剩余的值。

This works, but what should be the output if you have more elements in the input array?

这是可行的,但是如果在输入数组中有更多的元素,那么输出应该是什么呢?

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm');

function s($array, $am) {
    $r = array();
    $d = count($array) - $am+1;
    foreach ($array as $k => $v) {
        if ($k < $d) {
            if (!isset($r[0])) {
                $r[0] = array($v);
            } else {
                $r[0] = array_merge($r[0], array($v));
            }
        } else {
            $r[] = array($v);
        }
    }

    return $r;
}

will return

将返回

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
        )

    [2] => Array
        (
            [0] => d
        )

    [3] => Array
        (
            [0] => e
        )

    [4] => Array
        (
            [0] => f
        )

    [5] => Array
        (
            [0] => g
        )

    [6] => Array
        (
            [0] => h
        )

    [7] => Array
        (
            [0] => i
        )

    [8] => Array
        (
            [0] => j
        )

    [9] => Array
        (
            [0] => k
        )

    [10] => Array
        (
            [0] => l
        )

    [11] => Array
        (
            [0] => m
        )

)

#3


2  

You can use array_chunk and array_merge for this problem:

您可以使用array_chunk和array_merge来解决这个问题:

<?php 

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r');
$chunked_arr = array_chunk($array,12);
$j = 0;
for($i = 0; $i < count($chunked_arr[0]); $i++){
    if(!($i % 2 == 0)){
        $first_combined[$j][$i % 2] = $chunked_arr[0][$i];
        $j++;
    } else {
    $first_combined[$j][$i % 2] = $chunked_arr[0][$i];
    }
}

$merged_array = array_merge($first_combined, $chunked_arr[1]); 

echo '<pre>';
print_r($merged_array);
 ?>

And You will get the result like this:

你会得到这样的结果:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
            [1] => f
        )

    [3] => Array
        (
            [0] => g
            [1] => h
        )

    [4] => Array
        (
            [0] => i
            [1] => j
        )

    [5] => Array
        (
            [0] => k
            [1] => l
        )

    [6] => m
    [7] => n
    [8] => o
    [9] => p
    [10] => q
    [11] => r
)

This is what exactly you want.

这正是你想要的。

Live Demo Here>>

现场演示这里> >

#4


1  

ceil(count($array) / $parts) would give 2, so each array is being filled up with 2 items until you dont have 2 items left. hence the last one has 1 item. this will work when you have a huge amount of data in the array, but not so much when you have a small amount of data.

ceil(count($array) / $parts)会给出2,所以每个数组都被填充了2个条目,直到你没有剩下2个条目。因此最后一个有1个项。当数组中有大量数据时,这将起作用,但当您有少量数据时,就不会这么做了。

#5


1  

What you are describing is not what array_chunk is made for. You should use array_slice() and calculate yourself which parts of the array you want to end up as new arrays. (and use a for loop to iterate over your original array)

你所描述的并不是array_chunk所做的。您应该使用array_slice(),并计算自己希望作为新数组结束的数组的哪些部分。(并使用for循环遍历原始数组)

Update:

更新:

Some calculations that could help you:

一些计算可以帮助你:

minimum_fill = floor(array_length / nr_buckets)
bigger_buckets_amount = array_length - (minimum_fill / nr_buckets)

Algorithm to fill buckets: Loop over the array, fill the first bigger_buckets_amount amount of buckets with (minimum_fill + 1), fill the rest of the buckets with minimum_fill

算法来填充bucket:循环遍历数组,用(minimum_fill + 1)填充第一个较大的桶数,用minimum_fill填充其余的桶。

#6


1  

Compile that and see if it does for you:

编译它,看看它是否适合你:

<?php

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm');

$sliceA = 0;
$sliceB = 2;

$final = array(array_slice($array, $sliceA, $sliceB));


for ($i=$sliceB; $i<sizeof($array); $i++)
{
    $final[$sliceB-1] = array($array[$i]);
    $sliceB++;
}

var_dump($final);

#7


1  

<?php
$array = range('a','r');
$length = array(2=>6,1=>6); // 2=>6 means -- first six elements of new array will have 2 elements each and then, 1=>6 means -- next six elements of new array will have 1 element each
$target = array(); // or use []  in PHP 5.4
foreach($length as $i=>$times) {
    while($times>0){
        $target[] = array_splice($array, 0, $i);
        $times--;
    }
}
print_r($target);
?>

#8


1  

This will do it for you!
Here, I used my function smallify() to break an array of 15 elements into 3 arrays of 5 elements each.

这是为你做的!在这里,我使用了我的函数smallify()将15个元素的数组分解成3个数组,每个数组包含5个元素。

<?php

$bigArray = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);

echo ("<pre>");
print_r (smallify($bigArray, 3));
echo ("<pre/>");


function smallify($arr, $numberOfSlices){

  $sliceLength = sizeof($arr) /$numberOfSlices;
  for($i=1; $i<=$numberOfSlices; $i++){

       $arr1 = array_chunk($arr, $sliceLength*$i);
       return $arr1;
       unset($arr1);

   }

}
?>

Result

结果

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

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

[2] => Array
    (
        [0] => 11
        [1] => 12
        [2] => 13
        [3] => 14
        [4] => 15
    )

)

#9


0  

I believe the problem is that you are using a size of 2 when using array_chunk. This ensures that each new array created has two items in it if possible. This causes the function to run out of variables to put into the new arrays by the time you get to 10. You can find the manual on the function here http://php.net/manual/en/function.array-chunk.php Hope this helps

我认为问题是使用array_chunk时使用的是2的大小。这确保了每个新创建的数组都有两个项目。这将导致函数在您到达10时耗尽变量,并将其放入新的数组中。您可以在这里找到这个函数的手册http://php.net/manual/en/function.array-chunk.php希望这能有所帮助。