Исправлено условие PHP при декодировании JSON

Не сдавайтесь так быстро, потому что это можно сделать (в современных браузерах) с использованием частей FileAPI:

Редактировать 2017-09-28: Обновлено, чтобы использовать конструктор файлов, когда он доступен, поэтому работает в Safari> = 10.1.

Редактировать 2015-10-16: jQuery ajax не способен корректно обрабатывать двоичные ответы (не может установить responseType), поэтому лучше использовать простой вызов XMLHttpRequest.

var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
    if (this.status === 200) {
        var filename = "";
        var disposition = xhr.getResponseHeader('Content-Disposition');
        if (disposition && disposition.indexOf('attachment') !== -1) {
            var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            var matches = filenameRegex.exec(disposition);
            if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
        }
        var type = xhr.getResponseHeader('Content-Type');

        var blob = typeof File === 'function'
            ? new File([this.response], filename, { type: type })
            : new Blob([this.response], { type: type });
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
            // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
            window.navigator.msSaveBlob(blob, filename);
        } else {
            var URL = window.URL || window.webkitURL;
            var downloadUrl = URL.createObjectURL(blob);

            if (filename) {
                // use HTML5 a[download] attribute to specify filename
                var a = document.createElement("a");
                // safari doesn't support this yet
                if (typeof a.download === 'undefined') {
                    window.location = downloadUrl;
                } else {
                    a.href = downloadUrl;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                }
            } else {
                window.location = downloadUrl;
            }

            setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
        }
    }
};
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send($.param(params));

Вот старая версия, использующая jQuery.ajax. Он может искажать двоичные данные, когда ответ преобразуется в строку некоторой кодировки.

$.ajax({
    type: "POST",
    url: url,
    data: params,
    success: function(response, status, xhr) {
        // check for a filename
        var filename = "";
        var disposition = xhr.getResponseHeader('Content-Disposition');
        if (disposition && disposition.indexOf('attachment') !== -1) {
            var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            var matches = filenameRegex.exec(disposition);
            if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
        }

        var type = xhr.getResponseHeader('Content-Type');
        var blob = new Blob([response], { type: type });

        if (typeof window.navigator.msSaveBlob !== 'undefined') {
            // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
            window.navigator.msSaveBlob(blob, filename);
        } else {
            var URL = window.URL || window.webkitURL;
            var downloadUrl = URL.createObjectURL(blob);

            if (filename) {
                // use HTML5 a[download] attribute to specify filename
                var a = document.createElement("a");
                // safari doesn't support this yet
                if (typeof a.download === 'undefined') {
                    window.location = downloadUrl;
                } else {
                    a.href = downloadUrl;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                }
            } else {
                window.location = downloadUrl;
            }

            setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
        }
    }
});
1
задан A52 5 March 2019 в 20:41
поделиться

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);
            }

        }
    }
0
ответ дан geoidesic 5 March 2019 в 20:41
поделиться
Другие вопросы по тегам:

Похожие вопросы: