Reputation: 1055
I've an array like:
$array = array(
0 => "A",
1 => "B",
2 => "C",
3 => "D",
4 => "E",
5 => "F",
6 => "G",
7 => "H",
);
Max lenght $array
can be is 9, so max is index = 8
and min is 0 (at least 1 element inside array).
I've to indent this list inside a TCPDF box with limited height where, with some test, i've seen can support max 3 lines. But this box is large so, when the array lenght is bigger than 3, the others element need to be aligned in the side of the first column created like:
A D G
B E H
C F
I can't use X,Y coordinated cause i'm using writeHTML method in TCPDF.
I need to create 3 strings like:
$line1 = "A D G";
$line2 = "B E H";
$line3 = "C F";
What's the best method to create this 3 variables from my array?
UPDATE: using suggest method array_chunk is not the solution for me cause for my purpose I'd like to receive an array like:
Array ( [0] => Array (
[0] => A
[1] => D
[2] => G
)
[1] => Array (
[0] => B
[1] => E
[2] => H
)
[2] => Array (
[0] => C
[1] => F )
)
Upvotes: 0
Views: 647
Reputation: 1621
<?php
$array = array(
0 => "A",
1 => "B",
2 => "C",
3 => "D",
4 => "E",
5 => "F",
6 => "G",
7 => "H",
);
$array_chunk = array_chunk($array, 3,false);
$line = '';
foreach ($array_chunk as $chunk_key => $chunk_value) {
$line = '"';
foreach ($chunk_value as $key => $value) {
$line.=$value." ";
}
$line = "$" . "line" . ($chunk_key+1) . " = " . rtrim($line, " ") . '"' . "<br/>";
echo $line;
$line='';
}
Upvotes: 1
Reputation: 8415
I think a for
loop can solve OP's problem. This is another possible solution that use PHP array functions:
<?php
$array = array(
0 => "A",
1 => "B",
2 => "C",
3 => "D",
4 => "E",
5 => "F",
6 => "G",
7 => "H",
);
$cols = 3;
$array = array_chunk($array, $cols);
$results = array_map(function($index) use ($array) {
return array_column($array, $index);
}, range(0, $cols - 1));
var_dump($results);
View online here: https://eval.in/945787
Upvotes: 1