解码JSON时修复PHP条件

时间:2019-03-05 20:41:49

标签: php json

我正在使用php解码json文件。

foreach语句中,我检查cd_driver是否在来自json文件内容的数组中。如果在数组中,脚本将按预期更新其月份。如果没有,脚本将新驱动程序写入json文件。

一切正常,但是在更新月份并向json文件添加相同的驱动程序后,它也正在执行else条件。为什么会这样?

$dados[] = array('cd_driver' => $cd_driver, 'Driver' => $RSx["ds_name"], 'month' => $cd_month, 'bsaldo' => $saldoToJson);
$dados2 = array('cd_driver' => $cd_driver, 'Driver' => $RSx["ds_name"], 'month' => $cd_month, 'bsaldo' => $saldoToJson);
$jsonString = file_get_contents('bsaldo.json');
$data = json_decode($jsonString, true);

    if($data == ""){
        $newString = json_encode($dados);
        file_put_contents('bsaldo.json', $newString);
    }else {
        foreach ($data as $key => $value) {

            $mot = $value['cd_driver'];
            $array = array();
            array_push($array, $mot);

            if(in_array($cd_driver, $array)){
                $data[$key]['month'] = $cd_month;
                $newString = json_encode($data);
                file_put_contents('bsaldo.json', $newString);
            }else {
                array_push($data, $dados2);
                $finalString = json_encode($data);
                file_put_contents('bsaldo.json', $finalString);
            }

        }
    }

json:

[
    {
        "cd_driver": "11831",
        "Driver": "ADENILSON RODRIGUES DE SOUZA",
        "month": "02",
        "bsaldo": -903
    },
    {
        "cd_driver": "11835",
        "Driver": "EDIVAN DE CASTRO VASSALO",
        "month": "01",
        "bsaldo": -7670
    },
    {
        "cd_driver": "11831",
        "Driver": "ADENILSON RODRIGUES DE SOUZA",
        "month": "02",
        "bsaldo": -903
    },
    {
        "cd_driver": "11831",
        "Driver": "ADENILSON RODRIGUES DE SOUZA",
        "month": "02",
        "bsaldo": -903
    }
]

我不得不修改一些东西才能使用php 5.1。

1 个答案:

答案 0 :(得分:1)

您的问题是您要在循环的每次迭代中重置数组。像这样将其移到foreach之外:

$dados[] = array('cd_driver' => $cd_driver, 'Driver' => $RSx["ds_name"], 'month' => $cd_month, 'bsaldo' => $saldoToJson);
$dados2 = array('cd_driver' => $cd_driver, 'Driver' => $RSx["ds_name"], 'month' => $cd_month, 'bsaldo' => $saldoToJson);
$jsonString = file_get_contents('bsaldo.json');
$data = json_decode($jsonString, true);

    if($data == ""){
        $newString = json_encode($dados);
        file_put_contents('bsaldo.json', $newString);
    }else {
        $array = array(); # here it won't be continually reset and can accumulate values as intended.
        foreach ($data as $key => $value) {

            $mot = $value['cd_driver'];

            array_push($array, $mot);

            if(in_array($cd_driver, $array)){
                $data[$key]['month'] = $cd_month;
                $newString = json_encode($data);
                file_put_contents('bsaldo.json', $newString);
            }else {
                array_push($data, $dados2);
                $finalString = json_encode($data);
                file_put_contents('bsaldo.json', $finalString);
            }

        }
    }