如何用php存储json数据到mysql

时间:2017-04-27 08:50:15

标签: php json

这是我的json数据示例

[
    {"kode":"AX5","harga":"6200","status":"1","nama":"AXIS 5"},
    {"kode":"AX10","harga":"11250","status":"1","nama":"AXIS 10"},
    {"kode":"AX25","harga":"25750","status":"1","nama":"AXIS 25"},
    {"kode":"AX50","harga":"50800","status":"1","nama":"AXIS 50"}
]

我希望用php,field product_id,价格,状态,名称将数据保存到mysql,任何人都可以帮助我

我的问题是,我在php中不知道更好的代码

2 个答案:

答案 0 :(得分:3)

你可以使用PHP

json_decode()

将json字符串转换为PHP变量的函数。

然后,您可以获取这些值并将其保存到MySQL数据库;

来源json_decode PHP Manual

答案 1 :(得分:1)

您可以使用json_decode()。它需要一个JSON编码的字符串并将其转换为PHP变量。

  <?php
$json_data = '[{"kode":"AX5","harga":"6200","status":"1","nama":"AXIS 5"},{"kode":"AX10","harga":"11250","status":"1","nama":"AXIS 10"},{"kode":"AX25","harga":"25750","status":"1","nama":"AXIS 25"},{"kode":"AX50","harga":"50800","status":"1","nama":"AXIS 50"}]';
$array_data = json_decode($json_data);
echo '<pre>';
print_r($array_data);

foreach ($array_data as $event) {
    echo 'Product_id:' . $event->kode;
    echo "<br>";
    echo 'status:' . $event->status;
    echo "<br>";
}

然后输出

Array
(
    [0] => stdClass Object
        (
            [kode] => AX5
            [harga] => 6200
            [status] => 1
            [nama] => AXIS 5
        )

    [1] => stdClass Object
        (
            [kode] => AX10
            [harga] => 11250
            [status] => 1
            [nama] => AXIS 10
        )

    [2] => stdClass Object
        (
            [kode] => AX25
            [harga] => 25750
            [status] => 1
            [nama] => AXIS 25
        )

    [3] => stdClass Object
        (
            [kode] => AX50
            [harga] => 50800
            [status] => 1
            [nama] => AXIS 50
        )

)

Product_id:AX5
status:1
Product_id:AX10
status:1
Product_id:AX25
status:1
Product_id:AX50
status:1

了解更多信息

http://php.net/manual/en/function.json-decode.php