简体   繁体   中英

Split array using list and array_chunk for dynamic requirements

I am using list and array_chunk to split arrays. In my first example I split the array into four pieces using list.

I would like to change the number from 4 to say 8 and have it dynamically do this. Instead of manually creating it in the code. Is this possible ? I assume I could use variable naming as listed in my non working second example below.

How it works now :

list($inv0, $inv1, $inv2, $inv3) = array_chunk($val['inventory'], ceil(count($val['inventory']) / 4));

What I would like is to set something $i = 8 and have it automatically split into 8 chunks dynamically .

Something like :

$i = 8
list(${inv.0}, ${inv.1}, ${inv.2}, ${inv.3},${inv.4},${inv.5},${inv.6},${inv.7}) = array_chunk($val['inventory'], ceil(count($val['inventory']) / $i));

So based on my needs I can split the array into X pieces instead of hard coding it to 4 or 8 etc...

You can do a foreach to create the variables you want:

$array = ['a','b','c','d','e','f','g','h'];
$chunk = array_chunk($array,2);

foreach($chunk as $i => $data) {
    ${'inv'.$i} = $data;
}

print_r($inv0);
print_r($inv1);

die();

Output

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

There are ways, but I don't think it'd be a maintainable approach since you don't even know how many variables you'd need to process. However, Felipe Duarte provides a working answer and there are some more over here : php how to generate dynamic list()?

But I'd agree with the top answer. array_chunk already provides you with pretty much what you are looking for:

$chunks = array_chunk($val['inventory'], ceil(count($val['inventory']) / $i));
print_r($chunks); 
// [[0] => ['', ''], [1] => ['','']...]

You can then access it via the indices (such as $chunks[0] , $chunks[1] ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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