开发者

Splitting an array equally:

开发者 https://www.devze.com 2023-03-07 16:19 出处:网络
I have the following array: $array = array(1,0,0,0,1,1,1,1,0,1,1,1,1,0,1,1,0,1,0,0,1,0,1); I want split it up into individual arrays so that each array contains seven or less values.

I have the following array:

$array = array(1,0,0,0,1,1,1,1,0,1,1,1,1,0,1,1,0,1,0,0,1,0,1);

I want split it up into individual arrays so that each array contains seven or less values.

So for example the first array will become:

$one = array(1,0,0,0,1,1,1)
$two = array(1,0,1,1,1,1,0)
开发者_高级运维$three = array(1,1,0,1,0,0,1);
$four = array(0,1);

Also how would you count the number of times 1 occurs in array one?


array_chunk() is what you are looking for.

 $splitted = array_chunk($array, 7);

For counting the occurences I would be lazy. If your arrays only contain 1s or 0s, then a simple array_sum() would do:

 print array_sum($splitted[0]);    // for the first chunk


I want split it up into individual arrays so that each array contains seven or less values.

Use array_chunk(), which is made expressly for this purpose.

Also how would you count the number of times 1 occurs in array one?

Use array_count_values().

$one = array(1,0,0,0,1,1,1);
$one_counts = array_count_values($one);
print_r($one_counts);

// prints
Array
(
    [0] => 3
    [1] => 4
)


Assuming you want to preserve the contents of the array, I'd use array_slice() to extract the needed number of elements from the array, incrementing the '$offset' by the required count each time until the array was exhausted.

And as to your second question, try:

$num_ones=count(preg_grep(/^1$/,$array));
0

精彩评论

暂无评论...
验证码 换一张
取 消