首页 > 解决方案 > 使用 PHP 在 MySQL 中嵌套 JSON 存储

问题描述

我想就以下问题寻求您的帮助。

我得到了类似于下面在 PHP 中提到的嵌套 json。我想将数据存储在 MySQL db 中,但我遇到了变量信息的问题。

我的问题是数据不一致。正如您在下面的 json 中看到的:

   [6] => Array
        (
            [pflds] => Array
                (
                    [1] => Array
                        (
                            [id] => 1
                            [n] => registration_plate
                            [v] => xxxxxx
                        )

                    [2] => Array
                        (
                            [id] => 2
                            [n] => vehicle_type
                            [v] => xxxxx
                        )

                    [3] => Array
                        (
                            [id] => 3
                            [n] => brand
                            [v] => xxxx
                        )

                )

            [pfldsmax] => 0
        )

    [7] => Array
        (
            [pflds] => Array
                (
                    [1] => Array
                        (
                            [id] => 1
                            [n] => vehicle_type
                            [v] => Трактор
                        )

                    [2] => Array
                        (
                            [id] => 2
                            [n] => registration_plate
                            [v] => xxxxx
                        )

                    [3] => Array
                        (
                            [id] => 3
                            [n] => brand
                            [v] => John Deere
                        )

                )

            [pfldsmax] => 0
        )

一旦登记牌

数组 -> [6] -> [1] -> [n] 牌照

接着

数组 -> [7] -> [2] -> [n] 牌照

所以我不能轻易地说“插入”,因为列的位置不同。字段 [n] 在任何时候都具有相同的名称,但 [id] 可能会有所不同。

我想不出任何使用条件。但我想关注字段 [n] ,它将说明值将存储在哪一列中。

有什么建议或任何其他方法吗?

我是这个领域的新手。感谢您的帮助。

标签: phpmysqljson

解决方案


您可以foreach多次使用循环,例如:

foreach($ar as $ind1=>$set) {       // ind1 = 6 or 7
    foreach($set as $key=>$subar){  // key = 'pflds' or 'pfldsmax'
        if (is_array($subar)){      // if subar is an array
            foreach($subar as $item){
                if ($item['n'] === 'registration_plate'){
                    // code for insert into DB
                   echo $item['id'].PHP_EOL;
                }
            }
        }
    }
}

演示


推荐阅读