Jump to content

Custom array_chunk()


The Little Guy

Recommended Posts

I know PHP has an array_chunk function, but how would I duplicate that function into my own function?

 

Here is what I got so far:

<?php
function chunk($array, $amt){
for($i=0;$i<count($array);$i++){
	for($c=0;$c<$amt;$c++){
		if($c%$amt){
			$tempArray[$i][$c] = $array[($i+1)];
			$i = $i + 1;
		}else{
			$tempArray[$i][$c] = $array[$i];
		}
	}
}
return $tempArray;
}


$arr = array('1','2','3','4');
print_r(chunk($arr, 2));
?>

 

Edit:

 

Forgot to say:

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

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

)

 

See the second sub array, that should be a 1 not a 2, that is the problem I am having.

Link to comment
https://forums.phpfreaks.com/topic/143205-custom-array_chunk/
Share on other sites

Anyways, you are over-complicating it.  You don't need a for loop and a modulus.  You just need one or the other.  Modulus is cleaner so I'd go with that.

 

function chunk ($array, $size) {
   if (!is_array($array)) return false;

   $chunk = 0;
   $pos = 1;
   foreach ($array as $key => $val) {
      $newArray[$chunk][$key] = $val;
      if ($pos % $size == 0) $chunk++;
      $pos++;
   } // end foreach

   return $newArray;
} // end function chunk

Link to comment
https://forums.phpfreaks.com/topic/143205-custom-array_chunk/#findComment-751054
Share on other sites

I need to define the sub arrays, and I cant get it...

 

Any help?

function chunk ($array, $size) {
if (!is_array($array)) return false; 
$chunk = 0;
$pos = 1;
for($i=0;$i<count($array);$i++) {
	if(chunk % amt == 0){
		$tempArray[$chunk] = array();
	}
	$newArray[$chunk][$key] = $val;
	if ($pos % $size == 0) $chunk++;
	$pos++;
} // end foreach
return $newArray;
}

Link to comment
https://forums.phpfreaks.com/topic/143205-custom-array_chunk/#findComment-751418
Share on other sites

Oh do you mean define as in initialize them? 

 

function chunk ($array, $size) {
   if (!is_array($array)) return false;

   $chunk = 0;
   $pos = 1;
   foreach ($array as $key => $val) {
      if (!$newArray[$chunk]) $newArray[$chunk] = array();
      $newArray[$chunk][$key] = $val;
      if ($pos % $size == 0) $chunk++;
      $pos++;
   } // end foreach

   return $newArray;
} // end function chunk

Link to comment
https://forums.phpfreaks.com/topic/143205-custom-array_chunk/#findComment-751431
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.