简体   繁体   English

在PHP中使用数组存储多个值

[英]Storing multiple values using Arrays in PHP

i want to know how to insert the multiple array values by parent,child and subchild.I am having an array values as: 我想知道如何通过parent,child和subchild插入多个数组值。我有一个数组值如下:

Array
(
 [Gift] => Array
    (
        [SILVER] => Array
            (
                [0] => SILVER GLASS
                [1] => SILVER COIN GIFT
            )
    )
 [Electronics] => Array
    (
        [watch] => Array
            (
                [0] => Fasttrack
                [1] => Titan
            )
    )
 )

The Gift Array is the parent category, SILVER array is the subcategory for Gift and the third children array which is children for the SILVER. Gift数组是父类别,SILVER数组是Gift的子类别,而第三个child数组是SILVER的子类别。 How to insert the values by parent, child and subchildren dynamically? 如何按父,子和子子项动态插入值? Can you please help me how the array values insert using PHP and MySQL. 能否请您帮我如何使用PHP和MySQL插入数组值。

The best way is to use recursion, ex. 最好的方法是使用递归。

|  id  |     name      |  parent  |
    |   1  |  Electronics  |    0     |
    |   2  |     Watch     |    1     |

In parent column you need to save parent id, in example, there is row with name 'Electronics', and another with name 'Watch', first row have parent id '0' so it means that row is category, but another row have parent id 1, so that row is the child of Electronics. 在父列中,您需要保存父ID,例如,有一个行的名称为“ Electronics”,另一行的名称为“ Watch”,第一行的父ID为“ 0”,因此这意味着该行为类别,而另一行有父ID 1,因此该行是电子产品的子级。

I tried it having a table structure id_cat,cat_name,cat_parent 我尝试过具有表结构id_cat,cat_name,cat_parent

Code is: 代码是:

$arraytest=//given array;
repeateIt($arraytest,0);
function repeateIt($arr,$i) {
global $link;
foreach ($arr as $key => $value) {
    if(is_array($value)){
        $id=  mysqli_query($link,"INSERT INTO category values (NULL,'{$key}',{$i})");
        repeateIt($value,$i+1);
    }else{
        $id=  mysqli_query($link,"INSERT INTO category values (NULL,'{$value}',{$i})");
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM