简体   繁体   中英

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:

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

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.

I tried it having a table structure 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})");
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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