PHP开发:为指定结构数组编写添加行的函数需求
解决方案:给数组的
data字段添加多行数据 很简单,我们可以写几个实用的PHP函数来实现单行/批量添加,甚至直接从你的平行数组生成完整的data集合,下面一步步来:
1. 单行添加函数
这个函数负责把单条数据追加到data数组里,用引用传递直接修改原数组,不用返回新数组:
function addDataRow(array &$result, array $newRow): void { // 先确保`data`字段是数组(避免初始结构异常导致报错) if (!isset($result['data']) || !is_array($result['data'])) { $result['data'] = []; } // 追加新行到data末尾 $result['data'][] = $newRow; }
用法示例
假设你已经有了第二组数据($months[1]、$years[1]等),直接构造新行调用函数即可:
// 准备新的一行数据 $newRow = [ 'months' => $months[1], 'years' => $years[1], 'date' => $date[1], 'hr' => $hr[1], 'isms' => $isms[1], 'product' => $product[1], 'exploitation' => $exploitation[1] ]; // 把新行添加到原数组 addDataRow($result, $newRow);
2. 批量添加函数
如果要一次性加多条数据,用这个函数效率更高:
function addDataRows(array &$result, array $newRows): void { // 同样先确保data字段是数组 if (!isset($result['data']) || !is_array($result['data'])) { $result['data'] = []; } // 合并原data数组和新数据数组 $result['data'] = array_merge($result['data'], $newRows); }
用法示例
构造一个包含多行数据的数组,直接批量添加:
$newRows = [ [ 'months' => $months[1], 'years' => $years[1], 'date' => $date[1], 'hr' => $hr[1], 'isms' => $isms[1], 'product' => $product[1], 'exploitation' => $exploitation[1] ], [ 'months' => $months[2], 'years' => $years[2], 'date' => $date[2], 'hr' => $hr[2], 'isms' => $isms[2], 'product' => $product[2], 'exploitation' => $exploitation[2] ] ]; addDataRows($result, $newRows);
3. 直接从平行数组生成完整data(进阶)
如果你所有的字段数组($months、$years等)长度一致,可以用这个函数直接生成全部数据,省得一行一行加:
function populateData(array &$result, array $months, array $years, array $date, array $hr, array $isms, array $product, array $exploitation): void { $result['data'] = []; $totalRows = count($months); // 循环遍历所有索引,生成每一行数据 for ($i = 0; $i < $totalRows; $i++) { $result['data'][] = [ 'months' => $months[$i], 'years' => $years[$i], 'date' => $date[$i], 'hr' => $hr[$i], 'isms' => $isms[$i], 'product' => $product[$i], 'exploitation' => $exploitation[$i] ]; } }
用法示例
直接传入所有字段数组,就能生成完整的data集合:
// 注意:这个函数会覆盖原有的data数据,如果要保留原有数据,建议用前面的添加函数 populateData($result, $months, $years, $date, $hr, $isms, $product, $exploitation);
这些函数都做了容错处理,即使原数组的data字段不存在或者不是数组,也能正常工作,避免报错~
内容的提问来源于stack exchange,提问作者DavidDG
相关产品推荐
相关产品推荐

