phparraysmultidimensional-arraygroupingremap

Group array values based on array key suffix


I am trying to group my array values based on the array keys then print the result in the UI. I am stuck here for hours now.

Here is the array I need to format:

Array
(
    [checklist1] => major
    [result_audit1] => 1
    [checklist2] => minor
    [result_audit2] => 2
    [checklist3] => pico
    [result_audit3] => 3
    [checklist4] => goodpoints
    [result_audit4] => 4
    [submit] => Submit Now
)

Here is what I have tried so far but it is misaligned and not a proper result of the array.

foreach($n_data as $key => $data)
    {
        $array['checklist'][$i] = array(
            'selected' => $n_data[$key],
            'result_audit' => $n_data[$key]
        );

        $i++;
    }

Desired array:

Array
(
    [checklist] => Array
        (
            [0] => Array
                (
                    [selected] => major
                    [result_audit] => 1
                    [origin] => checklist1
                )

            [1] => Array
                (
                    [selected] => minor
                    [result_audit] => 2
                    [origin] => checklist2
                )
))

Solution

  • Parse the digital suffix of each checklist key and isolate the integer as a temporary value. As you iterate, if you encounter checklist data, push a new subarray into the result array which includes the related result_audit value.

    Code: (Demo)

    $result = [];
    foreach ($array as $k => $v) {
        if (sscanf($k, 'checklist%d', $integer)) {  // isolate integer only on "checklist" keyed elements
            $result['checklist'][] = [
                'selected' => $v,
                'result_audit' => $array["result_audit$integer"],
                'origin' => $k
            ];
        }
    }
    var_export($result);
    

    If the elegance of this answer isn't immediately obvious, it makes only one function call per iteration and doesn't need to use a regular expression to parse the keys.