Skip to main content
Changed title to follow CodeReview guidelines
Link

Refactoring nested foreach into functions Setting new values in array based on query results

Source Link

Refactoring nested foreach into functions

I have some code which uses nested foreach loops to take the results of a query and drill down into the data, reassigning into a main data array at each level of the foreach nesting. The problem is that required reference variables are passed into the loops deeper down the tree, making it difficult to refactor.

I'd like to refactor this into a more functional style. I've looked into array_walk() and array_map() to try and accomplish this but they seem to be more suited to amending the array argument rather than reassigning to an external array.

I'm looking more for general approaches to refactoring out foreach loops in PHP with this sort of context rather than a direct solution to my problem.

foreach($grid_fields as $gridFieldKey => $gridFieldValue) {
    $grid_field_id = $gridFieldValue['field_id'];
    $grid_field_str = 'field_id_' . $grid_field_id;
    $grid_entry = $this->fetchGridEntry($grid_field_id, $data['entry_id']);

    if(sizeOf($grid_entry) > 0) {
        $data[$grid_field_str] = array();
        $data[$grid_field_str]['entry_id'] = $cloned;

        foreach($grid_entry as $gridEntryKey => $gridEntryValue) {
            $grid_row = 'new_row_' . $gridEntryKey;
            $data[$grid_field_str]['rows'][$grid_row] = array();

            foreach($gridEntryValue as $geK => $geV) {
                if(strpos($geK, 'col_id_') !== false || strpos($geK, 'row_id') !== false) {
                    $data[$grid_field_str]['rows'][$grid_row][$geK] = $geV;
                }
            }
        }
    }
}