如何将人添加到mysql json数组?

时间:2019-01-23 17:45:15

标签: php mysql json

我在mysql中有一个像这样的2个人的json数组

{"people": [
            {"lastname": "Goodwill", "firstname": "James"}, 
            {"lastname": "Smith", "firstname": "Oliver"}
            ]
}

如何将新人员添加到阵列?我想我需要使用JSON_ARRAY_APPEND,但我不知道如何使用。表的名称=人员,列的名称= json_col,数组的名称=人员。我尝试过了,而且非常接近。

UPDATE person SET json_col = JSON_ARRAY_APPEND(json_col, "$.people", "lastname":"Jonsson", "firstname":"Kurt") WHERE id = '5';

但这给我的SQL语法带来了错误。

2 个答案:

答案 0 :(得分:0)

三个步骤:

  1. 将JSON转换为数组
  2. 将新值放入数组
  3. json_encode()数组

以下是代码(EXAMPLE):

$json = '{"people": [
            {"lastname": "Goodwill", "firstname": "James"}, 
            {"lastname": "Smith", "firstname": "Oliver"}
            ]
}';

$array = json_decode($json, true);
print_r($array);

$new_person = array("lastname" => "Yo", "firstname" => "Dog");
array_push($array['people'], $new_person);

print_r($array);

$updated = json_encode($array);

echo $updated;

以下是输出:

Array
(
    [people] => Array
        (
            [0] => Array
                (
                    [lastname] => Goodwill
                    [firstname] => James
                )

            [1] => Array
                (
                    [lastname] => Smith
                    [firstname] => Oliver
                )

        )

)
Array
(
    [people] => Array
        (
            [0] => Array
                (
                    [lastname] => Goodwill
                    [firstname] => James
                )

            [1] => Array
                (
                    [lastname] => Smith
                    [firstname] => Oliver
                )

            [2] => Array
                (
                    [lastname] => Yo
                    [firstname] => Dog
                )

        )

)
{"people":[{"lastname":"Goodwill","firstname":"James"},{"lastname":"Smith","firstname":"Oliver"},{"lastname":"Yo","firstname":"Dog"}]}

只要拥有数组,就可以使用它,直到需要输出JSON。

答案 1 :(得分:0)

我终于做到了。

更新人员SET json_col = JSON_ARRAY_APPEND(json_col,'$ .people',CAST('{“ lastname”:“ Jonsson”,“ firstname”:“ Kurt”}'as JSON))WHERE id ='5';

这是将新人添加到mysql json数组中的方式。