使用PHP将数组插入json

时间:2017-01-08 16:56:55

标签: php arrays json

我有一个从DB获取的IP地址列表,我需要将它们作为数组插入到json对象中。 这是json:

$jsonString="{
        \"id\": 1,
        \"type\": \"service\",
        \"name\": \"\",
        \"msg_types\": [6,7,8,9],
        \"billing_id\": 1,
        \"billing_name\":  \"\",
        \"ips\": \"\",
        \"callback_url\": \"\"
    }";
    $CBjson = json_decode($jsonString);
    $CBjson->id = (int)$id;
    $CBjson->name = $name;
    $CBjson->billing_name = $billing;
    $CBjson->billing_id = (int)$guid;
    $CBjson->ips = (array)$ips;
    $CBjson->callback_url = $callback;

从DB中获取的IP列表是一个字符串,如下所示: 11.222.111.555,11.222.111.148,11.222.121.555 现在,我得到: "ips": ["11.222.111.555, 11.222.111.148, 11.222.121.555"] 期望的结果是将IP列表作为json中的数组: "ips":["11.222.111.555", "11.222.111.148", "11.222.121.555"]

2 个答案:

答案 0 :(得分:0)

你应该这样做:

,

在这里,您可以通过ssh: connect to host 104.197.20.65 port 22: Operation timed out ERROR: (gcloud.compute.ssh) [/usr/bin/ssh] exited with return code [255]. See https://cloud.google.com/compute/docs/troubleshooting#ssherrors for troubleshooting hints. 分隔符来展开字符串。因此,您将拥有带有ip值的数组

答案 1 :(得分:0)

$ipString = '11.222.111.555,11.222.111.148,  11.222.121.555 ';

删除空格以使其保证安全:

$ipString = preg_replace('/\s*/', '', $ipString);

爆炸字符串:

$ipArray = explode(',', $ipString);

结果:

array(3) {
    [0] "11.222.111.555"
    [1] "11.222.111.148"
    [2] "11.222.121.555"
}