数组的合并和动态生成
需求说明
- 需要打印发货单数据,从数据库里面把发货数据查询出来进行打印,在打印之前需要对数据进行组装处理,然后代码内请求发送给 SDK 调用打印机。
- 在后台可以勾选要发货的数据,设置同一个备注,数据字段有 id,货位号,备注,和一些其它的字段。查询出来后需要把相同备注的数据添加到一个三维数组里面,同时把备注按照指定长度分割成一个数组。
- 在循环内判断分割后的备注数组长度和原始数组长度,足够发下备注不要处理,放不下的话要添加空数据,把备注展示出来。
代码示例
核心代码:
function establish() { $arr = []; $me_ser = []; // 动态生成的原始数据 for ($i=0;$i<5;$i++) { $iks = '这个的备注内容的文字,上下相同的合并到一个数组里面' . intval($i / 2); $me_ser[] = [ 'a' => $i+1, 'c' => $iks, 'd' => [ '这个的备注内容的文字',',上下相同的合并到','一个数组里面' //对 iks 按照指定长度分割的数组 ] ]; } $meg_arr = $this->mergeArrayObj($me_ser); // 进行合并操作 foreach ($meg_arr as $megItem) { $megItemCount = count($megItem); // 合并后的数组每一个的长度 $treeItem_d = 0; $three_num = 0; foreach ($megItem as $threeItem) { $three_num = count($threeItem['d']); $arr[]['map'] = [ $threeItem['a'], $threeItem['d'][$treeItem_d] ?? '', ]; $treeItem_d = $treeItem_d + 1; } // 动态处理 if ($megItemCount < $three_num) { $diff_num = $three_num - $megItemCount; for ($t = 0; $t < $diff_num; $t++) { $arr[]['map'] = [ '', $threeItem['d'][$treeItem_d] ?? '', ]; $treeItem_d = $treeItem_d + 1; } } $arr[]['map'] = ['---','---','---','---']; } return [$arr]; }
对数据合并处理:
function mergeArrayObj($originalArray) { $previousAValue = null; $resultArray = []; $currentSubArray = []; foreach ($originalArray as $item) { if ($item['c'] !== $previousAValue) { if (!empty($currentSubArray)) { $resultArray[] = $currentSubArray; } $currentSubArray = [$item]; $previousAValue = $item['c']; } else { $currentSubArray[] = $item; } } if (!empty($currentSubArray)) { $resultArray[] = $currentSubArray; } return $resultArray; }
按照指定长度分割
function splitStringByCharLength($string, $length) { $result = []; $len = mb_strlen($string, 'UTF-8'); $start = 0; while ($start < $len) { $end = min($start + $length, $len); $substr = mb_substr($string, $start, $end - $start, 'UTF-8'); $result[] = $substr; $start = $end; } return $result; }
本作品采用《CC 协议》,转载必须注明作者和本文链接