Reputation: 427
I have an multidimensional array which has images names and image label. This array sometimes gets as large as over 100K. I need to split this array into small chunks lets says 10K chunks as I need to get image name from each array and add that image which is stored locally into zip file.
Example of array:
Array (
[0] => Array ( [sku] => 1 [image] => 1-gbc.jpg [image_label] => 1 GBC EB100000)
[1] => Array ( [sku] => 2 [image] => 2-ib575037.jpg [image_label] => 2 IB575037)
[2] => Array ( [sku] => 3 [image] => 3-s0190303-paper-mate.jpg [image_label] => 3 Paper Mate S0190303 )
)
I need to split this into smaller chunks because it sometimes get impossible to add all the images for one array into single zip files which is why I need to create separate zip for each array chunk.
I have tried to user array_chunk but it is not working for me am I doing something wrong.
images = array_chunk($array, 10000);
Upvotes: 0
Views: 6141
Reputation: 1706
array_chunk()
should work for the example you've provided. The resulting array will have an extra level of depth, containing a numerically indexed array of your "chunks", which will follow the format of your original array.
$array = array(
array("sku" => 1,
"image" => "1-gbc.jpg",
"ib575037.jpg" => "1 GBC EB100000" ),
array("sku" => 2,
"image" => "ib575037.jpg",
"image label" => "2 IB575037" ),
array("sku" => 3,
"image" => "s0190303-paper-mate.jpg",
"image label" => "3 Paper Mate S0190303" ),
);
$array = array_chunk($array, 1);
foreach($array as $chunk)
{
foreach($chunk as $subarray)
{
echo "<pre>";
print_r($subarray);
echo "</pre>";
}
}
Hopefully this example will clear things up. Following this format should allow you to process each "chunk".
You're not just splitting an array, but turning it into chunks, so each resulting array will contain an array of chunks, and each of those chunks will contain however many values you've split the original array by.
Upvotes: 2
Reputation: 1192
You can split array using array_slice and then map it using array_map in order to get suitable output. Note that while you're free to change the order, it's wiser to first slice and then map due to performance reasons.
Upvotes: 0