I have some trouble re-building a PHP array. I need to change it for printing a table to a PDF doc with tfPDF Library.
I tried it with foreach loops, array_walk, array_walk_recursive, array_chunk and array_slice – so far without success.
This is my array $data:
Array
(
[file_id] => 1394
[user_id] => 463466
[periode] => 2022
[costs] => 64.45
[values] => Array
(
[457] => Array
(
[1] => Array
(
[data_id] => 1
[supplier_id] => 457
[costs1] => 1000
[costs2] => 100
[group_name] => 7%
)
[140] => Array
(
[data_id] => 140
[supplier_id] => 457
[costs1] => 2000
[costs2] => 50
[group_name] => 19%
)
[197] => Array
(
[data_id] => 197
[supplier_id] => 457
[costs1] => 3000
[costs2] => 300
[group_name] => special
)
)
[430] => Array
(
[490] => Array
(
[data_id] => 490
[supplier_id] => 430
[costs1] => 500
[costs2] => 30
[group_name] => new 4
)
[552] => Array
(
[data_id] => 552
[supplier_id] => 430
[costs1] => 7000
[costs2] => 250
[group_name] => new 5
)
)
[425] => Array
(
[1106] => Array
(
[data_id] => 1106
[supplier_id] => 425
[costs1] => 10
[costs2] => 4
[group_name] => new 6
)
)
)
)
For the print function the follwing format would be the best:
$pdf->Row(array(
"data_id n" .
"data_id n" .
"data_id",
"supplier_id n" .
"supplier_id n" .
"supplier_id",
"costs1 n" .
"costs1 n" .
"costs1",
"costs2 n" .
"costs2 n" .
"costs2",
"group_name n" .
"group_name n" .
"group_name",
));
So I need to change the $data to an array like this:
Array
(
[file_id] => 1394
[user_id] => 463466
[periode] => 2022
[costs] => 64.45
[values] => Array
(
[457] => Array
(
[data_id] => 1, 140, 197
[supplier_id] => 457, 457, 457
[costs1] => 1000, 2000, 3000
[costs2] => 100, 50, 300
[group_name] => 7%, 19%, special
)
[430] => Array
(
[data_id] => 490, 552
[supplier_id] => 430, 430
[costs1] => 500, 7000
[costs2] => 30, 250
[group_name] => new 4, new 5
)
[425] => Array
(
[data_id] => 1106
[supplier_id] => 425
[costs1] => 10
[costs2] => 4
[group_name] => new 6
)
)
)
Can you help me?
The last step would be the comma separation like this:
array_walk($data['values'], function (&$val) {
$val[] = implode(", ", $val[]);
});
2
Answers
A few loops and testings and it should work:
Output:
I would modify the original array, use nested loops to consolidate the structure, then update each subset of data in place.
Code: (Demo)