@@ -83,6 +83,13 @@ class Table
83
83
*/
84
84
public $ function ;
85
85
86
+ /**
87
+ * Order each inserted row by heading keys
88
+ *
89
+ * @var bool
90
+ */
91
+ public bool $ rowKeysSyncWithHeadingKeys = false ;
92
+
86
93
/**
87
94
* Set the template from the table config file if it exists
88
95
*
@@ -162,6 +169,7 @@ public function makeColumns($array = [], $columnLimit = 0)
162
169
// Turn off the auto-heading feature since it's doubtful we
163
170
// will want headings from a one-dimensional array
164
171
$ this ->autoHeading = false ;
172
+ $ this ->rowKeysSyncWithHeadingKeys = false ;
165
173
166
174
if ($ columnLimit === 0 ) {
167
175
return $ array ;
@@ -207,7 +215,42 @@ public function setEmpty($value)
207
215
*/
208
216
public function addRow ()
209
217
{
210
- $ this ->rows [] = $ this ->_prepArgs (func_get_args ());
218
+ $ tmpRow = $ this ->_prepArgs (func_get_args ());
219
+
220
+ if ($ this ->rowKeysSyncWithHeadingKeys && !empty ($ this ->heading )) {
221
+ // each key has an index
222
+ $ keyIndex = array_flip (array_keys ($ this ->heading ));
223
+
224
+ // figure out which keys need to be added
225
+ $ missingKeys = array_diff_key ($ keyIndex , $ tmpRow );
226
+
227
+ // Remove all keys which don't exist in $keyIndex
228
+ $ tmpRow = array_filter ($ tmpRow , static fn ($ k ) => array_key_exists ($ k , $ keyIndex ), ARRAY_FILTER_USE_KEY );
229
+
230
+ // add missing keys to row, but use $this->emptyCells
231
+ $ tmpRow = array_merge ($ tmpRow , array_map (fn ($ v ) => ['data ' => $ this ->emptyCells ], $ missingKeys ));
232
+
233
+ // order keys by $keyIndex values
234
+ uksort ($ tmpRow , static fn ($ k1 , $ k2 ) => $ keyIndex [$ k1 ] <=> $ keyIndex [$ k2 ]);
235
+ }
236
+ $ this ->rows [] = $ tmpRow ;
237
+
238
+ return $ this ;
239
+ }
240
+
241
+ /**
242
+ * Set to true if each row column should be synced by keys defined in heading.
243
+ *
244
+ * If a row has a key which does not exist in heading, it will be filtered out
245
+ * If a row does not have a key which exists in heading, the field will stay empty
246
+ *
247
+ * @param bool $orderByKey
248
+ *
249
+ * @return Table
250
+ */
251
+ public function setSyncRowKeysWithHeadingKeys (bool $ orderByKey ): Table
252
+ {
253
+ $ this ->rowKeysSyncWithHeadingKeys = $ orderByKey ;
211
254
212
255
return $ this ;
213
256
}
@@ -436,7 +479,8 @@ protected function _setFromArray($data)
436
479
}
437
480
438
481
foreach ($ data as &$ row ) {
439
- $ this ->rows [] = $ this ->_prepArgs ($ row );
482
+ $ this ->addRow ($ row );
483
+ //$this->rows[] = $this->_prepArgs($row);
440
484
}
441
485
}
442
486
0 commit comments