页、行和列中的块数组
Chunk array in pages, rows and columns
我想在 PDF 文件(水平方向)中显示一个大的 table,在多个页面上,数据数组来自我的数据库。每页应有 8 列。所以结果数组有页,有行,有列。
我已经尝试了 for 循环的不同组合,但无法弄清楚..
我的数据结构:
$data = [
[
'name' => 'Item_1',
'id' => 1243123
],
[
'name' => 'Item_2',
'id' => 1789435
],
...
[
'name' => 'Item_8',
'id' => 4513531
],
[
'name' => 'Item_9',
'id' => 352790
],
...
[
'name' => 'Item_12',
'id' => 643563
],
];
我想要的数据结构:
$result = [
[
['Item_1', 'Item_2', ... , 'Item_8'],
[1243123, 1789435, ... , 4513531]
],
[
['Item_9', ... , 'Item_12'],
[352790, ... , 643563]
]
];
我这样试过:
$data = array_chunk($fromDatabase, 8);
$result = [];
$pages = count($data);
// For each Page
for ($i = 0; $i < $pages; $i++) {
// Add Rows to Page
for ($r = 0; $r < count($data[$i]); $r++) {
$result[$p][$r][] = $data[$i][0];
}
}
以及许多其他循环结构。
首先,您可以使用 array_column next, you can chunk each column array into the size you want with array_chunk.
将原始数据分成单独的数组
最后,将两个分块数组合并。
$nameChunks = array_chunk(array_column($data, 'name'), 8);
$idChunks = array_chunk(array_column($data, 'id'), 8);
$result = [];
foreach($nameChunks as $key => $names) {
$result[] = [
$names,
$idChunks[$key],
];
}
如果您有任何问题,请告诉我。
我想在 PDF 文件(水平方向)中显示一个大的 table,在多个页面上,数据数组来自我的数据库。每页应有 8 列。所以结果数组有页,有行,有列。
我已经尝试了 for 循环的不同组合,但无法弄清楚..
我的数据结构:
$data = [
[
'name' => 'Item_1',
'id' => 1243123
],
[
'name' => 'Item_2',
'id' => 1789435
],
...
[
'name' => 'Item_8',
'id' => 4513531
],
[
'name' => 'Item_9',
'id' => 352790
],
...
[
'name' => 'Item_12',
'id' => 643563
],
];
我想要的数据结构:
$result = [
[
['Item_1', 'Item_2', ... , 'Item_8'],
[1243123, 1789435, ... , 4513531]
],
[
['Item_9', ... , 'Item_12'],
[352790, ... , 643563]
]
];
我这样试过:
$data = array_chunk($fromDatabase, 8);
$result = [];
$pages = count($data);
// For each Page
for ($i = 0; $i < $pages; $i++) {
// Add Rows to Page
for ($r = 0; $r < count($data[$i]); $r++) {
$result[$p][$r][] = $data[$i][0];
}
}
以及许多其他循环结构。
首先,您可以使用 array_column next, you can chunk each column array into the size you want with array_chunk.
将原始数据分成单独的数组最后,将两个分块数组合并。
$nameChunks = array_chunk(array_column($data, 'name'), 8);
$idChunks = array_chunk(array_column($data, 'id'), 8);
$result = [];
foreach($nameChunks as $key => $names) {
$result[] = [
$names,
$idChunks[$key],
];
}
如果您有任何问题,请告诉我。