有没有更好的方法来循环遍历2d数组行在php中

时间:2019-10-18 06:12:50

标签: php arrays loops foreach

我正在通过2D数组上的循环在表中插入多个数据。

这是我的数据

$data['id'] = array([0] => '1', [1] => '2');
$data['name'] = array([0] => 'Ben', [1] => 'Dan');
$data['status'] = array([0] => 'Active', [1] => 'Active');
$data['updatedby'] = '1';
$data['updateddate'] = date('d-M-y H:i');
$idColumn = 'id';
$table = 'tablename';

这是我的代码:

foreach($data as $key => $value){
    $i = 0;
    if($key <> 'updatedby' && $key <> 'updateddate'){
        foreach($value as $row){
            $result = $this->myModel->recordUpdate($idColumn, $data['id'][$i], array($key => $row), $table);
            $i = $i + 1;
        }
    }

    if($key == 'updatedby'){
        foreach($data['id'] as $row){
            $result = $this->myModel->recordUpdate($idColumn, $row, array($key => $data['updatedby']), $table);
        }
    }

    if($key == 'updateddate'){
        foreach($data['id'] as $row){
            $result = $this->myModel->recordUpdate($idColumn, $row, array($key => $data['updateddate']), $table);
        }
    }
}

function recordUpdate($idColumn, $id, $data, $table)
{
    $this->db->where($idColumn, $id);
    $this->db->update($table, $data);
    $update_id = $this->db->affected_rows();

    return $update_id;
}

有什么办法可以使行先通过行然后通过列进行主循环,我想使这段代码更短,更可靠。

1 个答案:

答案 0 :(得分:1)

您可以通过首先过滤和转置主要数据来做到这一点:

$rows = array_transpose(array_filter($data, function($key){
    return !in_array($key, ["updatedby","updateddate"]);
}, ARRAY_FILTER_USE_KEY));

function array_transpose($array){
    $keys = array_keys($array);
    $new_array = [];
    for($i = 0, $len = count($array[$keys[0]]); $i < $len; $i++){
        $new_array[$i] = [];
        foreach($keys as $key){
            $new_array[$i][$key] = $array[$key][$i];
        }
    }
    return $new_array;
}

然后您可以像这样遍历行:

for($row = 0, $cnt = count($rows); $row < $cnt; $row++){
    $column_data = $rows[$row];
    $column_keys = array_keys($column_data);
    $column_id = $column_data[$idColumn];
    foreach($column_keys as $key){
       recordUpdate(
           $idColumn,
           $column_id,
           [$key => $column_data[$key]],
           $table
       );
   }

   // set the updatedby and updateddate for each row
   $this->myModel->recordUpdate($idColumn, $column_id, ["updatedby" => $data["updatedby"]], $table);
   $this->myModel->recordUpdate($idColumn, $column_id, ["updateddate" => $data["updateddate"]], $table);
}