简体   繁体   中英

Array into chunks and results by chunks in a new line with php

So as a title says: I have an array

array(0=>"a"1=>"b"2=>"c"3=>"d"4=>"e"5=>"f")

What I want to do is loop through and chunk results and print them like this

ab cd ef

OR

abc def

So far I got this: I chunked array with array_chunk() like this

$chunks = array_chunk($my_array, 3);

So it gives me result like this:

Array(0 => array(0=>"a"1=>"b"2=>"c")1=>array(4=>"d"5=>"e"6=>"f"))

So I loop through

foreach($chunks as $key => $value){
   echo $value.'<br>';}

Current output:

abcdef

Desire output:

abc def

Any Ideas?

Also I'm on laravel just in case anyone knows a specific approach

Since this is tagged with laravel I assume you want a laravel answer too(?).

You can use the chunk function that comes with laravel

$collection = collect([1, 2, 3, 4, 5, 6, 7]);

$chunks = $collection->chunk(4);

$chunks->toArray();

// [[1, 2, 3, 4], [5, 6, 7]]

The chunks you created are array.

You can prints them when using:

$arr= array(0=>"a",1=>"b",2=>"c",3=>"d",4=>"e",5=>"f");
$chunks = array_chunk($arr, 3);
foreach($chunks as $key => $value)
    echo implode("",$value). "\n";

Output:

abc
def

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