使用动态数据在PHP中创建多维数组

时间:2022-08-26 21:35:10

I am preparing a menu system for a restaurant which provides food on a monthly basis. This is my problem:

我正准备一个餐厅的菜单系统,每月提供食物。这是我的问题:

There are different packages that the restaurant offers. Each package consists of a number of servings each day. For example, package A serves 3 times a day, whereas package B serves 2 times a day. The online ordering system that I am building is a multi-page ordering system divided as per the number of days. So for 20 days, there are 20 pages. Once the selection of one day is completed, I want to store the selection in a multi-dimensional array. Refer to the below structure for reference.

餐厅提供不同的套餐。每个套餐每天包含许多份。例如,包装A每天服用3次,而包装B每天服务2次。我正在建立的在线订购系统是按照天数划分的多页订购系统。因此,20天,有20页。一旦选择了一天,我想将选择存储在一个多维数组中。请参考以下结构以供参考。

$selection_package_a = array( 
   "Serving_Day1" => array (
      "Serving_1" => Pizza,
      "Serving_2" => Salad, 
      "Serving_3" => Smoothies
   ),
   "Serving_Day2" => array (
      "Serving_1" => Salad,
      "Serving_2" => Juices,    
      "Serving_3" => Fruits
   ),
);

$selection_package_b = array( 
   "Serving_Day1" => array (
      "Serving_1" => Pizza,
      "Serving_2" => Salad
   ),
   "Serving_Day2" => array (
      "Serving_1" => Salad,
      "Serving_2" => Juices
   ),
);

"Serving_Day1" to "Serving_Day20" depends on the number of days served during a month. So if the package serves only 10 days a month, then "Serving_Day10" will be the last field.

“Serving_Day1”到“Serving_Day20”取决于一个月内服务的天数。因此,如果该套餐每月只提供10天,那么“Serving_Day10”将是最后一个字段。

Within "Serving_Day1", "Serving_1" and so on depends on the number of servings stored in the database.

在“Serving_Day1”,“Serving_1”等内部取决于数据库中存储的服务数量。

Taking the answer of @yarwest a step forward, I have pasted the progress till now. I guess it is just one more step to acheive the desired output.

在@yarwest的答案向前迈进了一步,我已经将进展粘贴到现在。我想这只是实现所需输出的又一步。

$meals_selected_array = [];

$total_meals_array = [];

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'];

        //repeating it based on the number of days_served
        for ($i = 1; $i <= $days_served; $i++) {
            //how to define/declare $total_meals_array['day_' . $i]            

            //adding user selection for the day in $meals_selected_array array
            for ($y = 1; $y <= $servings_count; $y++) {
                $meals_selected_array["meal_id_day_" .$i] = "Not Available";
                $meals_selected_array["meal_code_day_" .$i] = "Not Available";
                $meals_selected_array["meal_type_day_" .$i] = "Meal";
            }

            //what to do either here or after the below loop in order to add $meals_selected_array above values to $total_meals_array['day_' . $i].
        }          
    }
}

When I $print_r($meals_selected_array), I get the result as an Associative Array with perfect labelling and values. Now I just have to add this Associative Array to each day to make my primary Array as a Multidimensional Array.

当我$ print_r($ meals_selected_array)时,我得到的结果是一个具有完美标签和值的关联数组。现在我只需每天添加这个关联数组,使我的主数组成为多维数组。

So my desired output for $total_meals_array is as below:

所以我想要的$ total_meals_array输出如下:

Array
(
    [day_1] => Array
        (
            [meal_id_day_1] => "1" //This will be my Unique ID of selected meal
            [meal_code_day_1] => "Pizza" //This will be the name of meal
            [meal_type_day_1] => "Main Course" //This will be the serving Type
        )

    [day_2] => Array
        (
            [meal_id_day_2] => "4" //This will be my Unique ID of selected meal
            [meal_code_day_2] => "Lemonade" //This will be the name of meal
            [meal_type_day_2] => "Drinks" //This will be the serving Type
        )

    [day_3] => Array
        (
            [meal_id_day_3] => "8" //This will be my Unique ID of selected meal
            [meal_code_day_3] => "Custard" //This will be the name of meal
            [meal_type_day_3] => "Dessert" //This will be the serving Type
        )

)

2 个解决方案

#1


0  

Important note beforehand

It is very unsafe to use mysqli functions. They can easily be manipulated with, for example, SQL injections. Instead use PDO and Prepared Statements.

使用mysqli函数非常不安全。例如,可以使用SQL注入轻松操作它们。而是使用PDO和Prepared Statements。

The solution

You retrieved a package from the database. The next step is to loop based on the amount of servings and amount of days to create a new array to hold the package.

您从数据库中检索了一个包。下一步是根据服务量和创建新数组以保存包的天数进行循环。

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'];

        //Create a new array to hold the servings skeleton
        $servingsArray = [];
        //For every serving add an empty string to the servingArray
        for($i = 0; $i < $servings_count; $i++){
            array_push(
                $servingsArray,
                ""
            );
        }

        //Create a new array to hold the package skeleton
        $selection_package = [];
        //For every day add an servingArray to the package array
        for($i = 0; $i < $days_served; $i++){
            array_push(
                $selection_package,
                $servingsArray
            );
        }           
    }
}

This will create an entirely empty array according to the specified structure.

这将根据指定的结构创建一个完全空的数组。

#2


0  

Now here is the code that works best in the given situation.

现在这里是在给定情况下效果最好的代码。

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_id(唯一字段)

  3. package_name (Name of the Package, e.g. Package A)
  4. package_name(包的名称,例如包A)

  5. servings_count (Total Servings in a Day)
  6. servings_count(一天的总份量)

  7. days_served (Number of Days Served in a Month)
  8. days_served(一个月内服务的天数)

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.

为了将每天的膳食选择和当天的服务作为订单存储在数据库中,我需要一个可以动态定义/填充的多维PHP数组。

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.

首先,我们必须声明两个PHP数组。

$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:

执行此操作后,运行MySQL查询以从数据库中读取包。现在根据结果,执行以下操作:

$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.

谢谢大家,特别是@yarwest,我很友好地回答了我的问题。

#1


0  

Important note beforehand

It is very unsafe to use mysqli functions. They can easily be manipulated with, for example, SQL injections. Instead use PDO and Prepared Statements.

使用mysqli函数非常不安全。例如,可以使用SQL注入轻松操作它们。而是使用PDO和Prepared Statements。

The solution

You retrieved a package from the database. The next step is to loop based on the amount of servings and amount of days to create a new array to hold the package.

您从数据库中检索了一个包。下一步是根据服务量和创建新数组以保存包的天数进行循环。

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'];

        //Create a new array to hold the servings skeleton
        $servingsArray = [];
        //For every serving add an empty string to the servingArray
        for($i = 0; $i < $servings_count; $i++){
            array_push(
                $servingsArray,
                ""
            );
        }

        //Create a new array to hold the package skeleton
        $selection_package = [];
        //For every day add an servingArray to the package array
        for($i = 0; $i < $days_served; $i++){
            array_push(
                $selection_package,
                $servingsArray
            );
        }           
    }
}

This will create an entirely empty array according to the specified structure.

这将根据指定的结构创建一个完全空的数组。

#2


0  

Now here is the code that works best in the given situation.

现在这里是在给定情况下效果最好的代码。

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_id(唯一字段)

  3. package_name (Name of the Package, e.g. Package A)
  4. package_name(包的名称,例如包A)

  5. servings_count (Total Servings in a Day)
  6. servings_count(一天的总份量)

  7. days_served (Number of Days Served in a Month)
  8. days_served(一个月内服务的天数)

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.

为了将每天的膳食选择和当天的服务作为订单存储在数据库中,我需要一个可以动态定义/填充的多维PHP数组。

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.

首先,我们必须声明两个PHP数组。

$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:

执行此操作后,运行MySQL查询以从数据库中读取包。现在根据结果,执行以下操作:

$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.

谢谢大家,特别是@yarwest,我很友好地回答了我的问题。