How to group an array into subarrays using its keys? How to group an array into subarrays using its keys? json json

How to group an array into subarrays using its keys?


Man that is very specific use case for arrays. Well here is your solution.

$array = <YOUR SAMPLE ARRAY>$output = [];/* * Nesting array based on a_id, b_id */foreach ($array as $item) {    $aid = $item['a_id'];    $bid = $item['b_id'];    $cid = $item['c_id'];    if(!isset($output[$aid])){        $output[$aid] = [            'a_id' => $item['a_id'],            'a_name' => $item['a_name'],            'b_list' => [                $bid => [                    'b_id' => $item['b_id'],                    'b_name' => $item['b_name'],                    'c_list' => [                        $cid = [                            'c_id' => $item['c_id'],                            'c_name' => $item['c_name']                        ]                    ]                ]            ]        ];    } else if (!isset($output[$aid]['b_list'][$bid])){        $output[$aid]['b_list'][$bid] =  [            'b_id' => $item['b_id'],            'b_name' => $item['b_name'],            'c_list' => [                $cid => [                    'c_id' => $item['c_id'],                    'c_name' => $item['c_name']                ]            ]        ];    } else if(!isset($output[$aid]['b_list'][$bid]['c_list'][$cid])) {        $output[$aid]['b_list'][$bid]['c_list'][$cid] = [            'c_id' => $item['c_id'],            'c_name' => $item['c_name']        ];    } else {        // Do/Dont overrider    }}/* * Removing the associativity from the b_list and c_list */function indexed($input){    $output = [];    foreach ($input as $key => $item) {        if(is_array($item)){            if($key == 'b_list' || $key == 'c_list'){                $output[$key] = indexed($item);            } else {                $output[] = indexed($item);            }        } else {            $output[$key] = $item;        }    }    return $output;}$indexed = indexed($output);print_r(json_encode($indexed, 128));


Interesting requirement there.Here is my generalized solution that is also extendable.

function transform($array, $group=[    ['a_id','a_name','b_list'],    ['b_id','b_name','c_list'],    ['c_id','c_name'],]){    foreach($array as $a){        $r = &$result;        foreach($group as $g){            $x = &$r[$a[$g[0]]];            $x[$g[0]] = $a[$g[0]];            $x[$g[1]] = $a[$g[1]];            if(isset($g[2])) $r = &$x[$g[2]]; else break;        }    }    return transformResult($result);}function transformResult($result){    foreach($result as &$a)        foreach($a as &$b)            if(is_array($b)) $b = transformResult($b);    return array_values($result);}

To extend this solution, all you have to do is modify the $group parameter,either directly in the function declaration or by passing an appropriate value as the 2nd parameter.

Usage example:

echo json_encode(transform($array), JSON_PRETTY_PRINT);

This will return the same output assuming the same $array input in your example.


Now here is the code that works best in the given situation. I have created a similar situation and then explained the solution in detail.

Situation
The Order Form is multipage depending on the number of days served based on the package selected. Details of each package are stored in the database with the following fields:

  1. package_id (Unique Field)
  2. package_name (Name of the Package, e.g. Package A)
  3. servings_count (Total Servings in a Day)
  4. days_served (Number of Days Served in a Month)

In order to carry forward the selection of meals for each day and serving of that day to store as an Order in the database, I required a Multidimensional Array of PHP that can be defined/populated dynamically.

Expected output is something like:

Array(    [Day 1] => Array        (            [meal_id_1] => Unique ID //to be replaced with user selection            [meal_code_1] => Meal Name //to be replaced with user selection            [meal_type_1] => Meal //prefilled based on the selected package            [meal_id_2] => Not Available //to be replaced with user selection            [meal_code_2] => 2 //to be replaced with user selection            [meal_type_2] => Meal //prefilled based on the selected package        )    [Day 2] => Array        (            [meal_id_1] => Unique ID //to be replaced with user selection            [meal_code_1] => Meal Name //to be replaced with user selection            [meal_type_1] => Meal //prefilled based on the selected package            [meal_id_2] => Not Available //to be replaced with user selection            [meal_code_2] => 2 //to be replaced with user selection            [meal_type_2] => Meal //prefilled based on the selected package        )

This above array has been created 100% dynamically based on the explained structure and number of servings and days. Below is the code with some explanation.

First, we have to declare two PHP Arrays.

$total_meals_array = []; //Primary, Multidimension Array$meals_selected_array = []; //Meals Details Array to be used as primary array's key value.

After doing this, run MySQL query to read packages from the database. Now based on the result, do the following:

$total_meals_array = []; //Primary, Multidimension Array$meals_selected_array = []; //Meals Details Array to be used as primary array's key value.if( $num_row_packages >= 1 ) {    while($row_packages = mysqli_fetch_array ($result_packages)) {        $package_id = $row_packages['package_id'];        $package_name = $row_packages['package_name'];        $servings_count = $row_packages['servings_count'];        $days_served = $row_packages['days_served'];        //this for loop is to repeat the code inside `$days_served` number of times. This will be defining our primary and main Multidimensional Array `$total_meals_array`.        for ($y = 1; $y <= $days_served; $y++) {            //once inside the code, now is the time to define/populate our secondary array that will be used as primary array's key value. `$i`, which is the meal count of each day, will be added to the key name to make it easier to read it later. This will be repeated `$meals_count` times.            for ($i = 1; $i <= $meals_count; $i++) {                $meals_selected_array["meal_id_" . $i] = "Unique ID";                $meals_selected_array["meal_code_" . $i] = "Meal Name";                $meals_selected_array["meal_type_" . $i] = "Meal";            }            //once our secondary array, which will be used as the primary array's key value, is ready, we will start defining/populating our Primary Multidimensional Array with Keys Named based on `$days_served`.            $total_meals_array["Day " . $y] = $meals_selected_array;        }    }}

That's it! Our dynamic Multidimensional Array is ready and can be viewed by simply the below code:

print "<pre>";print_r($total_meals_array);print "</pre>";

Thank you everyone, specially @yarwest for being kind enough to answer my question.