为什么PHP总是覆盖JSON文件中的相同字符串?

时间:2018-04-15 12:10:49

标签: php json

我正在尝试将用户添加到json,但每次它都会覆盖该字符串,结果发现有一个用户。我正确地描述了每条线的作用?但为什么要重写?

$ input = json_decode ($ _ POST ["phones"], true);
// that's what's in `input`-if that's what.
// $ input = '[["5345", "345345", "123"], "Michael", "Podlevskykh"]';

$ file = file_get_contents ('jsn.json'); // get the file
$ output = json_decode ($ file, TRUE); // decode
unset ($ file); // clean the variable

// then add to JSON
$ output = [
    'user2' => [
        'first_name' => $ input [1],
        'last_name' => $ input [2],
        'phones' => [
            'phone_1' => $ input [0] [0],
            'phone_2' => $ input [0] [1],
            'phone_3' => $ input [0] [2]
        ]
    ]
];

file_put_contents ('jsn.json', json_encode ($ output)); // convert to string
unset ($ output); // clean

1 个答案:

答案 0 :(得分:1)

您需要使用$output$output[] = $new_data将新数组附加到array_push($output, $new_data)。在您的实际代码中,您将使用新值分配数组,因此您只获得最后一个元素。

$output[] = [
    'user2' => [
        'first_name' => $input[1],
        'last_name' => $input[2],
        'phones' => [
            'phone_1' => $input[0][0],
            'phone_2' => $input[0][1],
            'phone_3' => $input[0][2]
        ]
    ]
];