file_put_content数组结构不起作用

时间:2017-08-18 21:24:04

标签: javascript php jquery arrays json

我试图将数组移动到.json文件中,然后简单地调试它。我认为我的阵列中的结构搞砸了。

$jsonarray = array('Symbol'=>[$symbol],'PERatio'=>[$peratio], 'MarketCap'=>[$marketcap], 'Dividend'=>[$dividend], 'ROE'=>[$roe], 'DebtToEbitda'=>[$debttoebitda], 'EbitdaGrowth' =>[$ebitdagrowth],  'RevenueGrowth' =>[$revenuegrowth],);
file_put_contents('Stockdata1.json', json_encode($jsonarray), FILE_APPEND);

这就是.json文件中的样子。

{"Symbol":["A"],"PERatio":["31.55"],"MarketCap":["19722.500"],"Dividend":["0.87"],"ROE":["14.48"],"DebtToEbitda":["2.04"],"EbitdaGrowth":["5.40"],"RevenueGrowth":["4.20"]}{"Symbol":["AA"],"PERatio":["44.45"],"MarketCap":["6960.660"],"Dividend":["0.00"],"ROE":["2.33"],"DebtToEbitda":["0.95"],"EbitdaGrowth":["0.00"],"RevenueGrowth":["0.00"]}{"Symbol":["AAC"],"PERatio":["0.00"],"MarketCap":["217.730"],"Dividend":["0.00"],"ROE":["-2.76"],"DebtToEbitda":["8.71"],"EbitdaGrowth":["22.30"],"RevenueGrowth":["15.00"]}{"Symbol":["AAP"],"PERatio":["18.68"],"MarketCap":["6888.440"],"Dividend":["0.26"],"ROE":["12.69"],"DebtToEbitda":["1.17"],"EbitdaGrowth":["6.50"],"RevenueGrowth":["13.60"]}

然后我尝试在这样的js中调试console.log

    $.getJSON('Stockdata1.json', function (data) {
            console.log(data);
    });
什么都没有出来......希望有人能看出我的错误..

1 个答案:

答案 0 :(得分:1)

只要您FILE_APPEND第二个数组,就会使文件中的JSON无效。该文件将包含两个没有分隔符的JSON对象(即(为了清晰起见){"Symbol":["A"]}{"Symbol":["B"]})。

相反,您需要有效的JSON,就是让文件包含所有对象的JSON数组:[{"Symbol":["A"]},{"Symbol":["B"]}]。唯一的方法是不要将file_put_contents()FILE_APPEND标志一起使用,而是将文件作为JSON加载,添加新对象,并将完整的JSON写回文件。

我的建议是将代码更改为以下内容:

$jsonarray = array('Symbol'=>[$symbol],'PERatio'=>[$peratio], 'MarketCap'=>[$marketcap], 'Dividend'=>[$dividend], 'ROE'=>[$roe], 'DebtToEbitda'=>[$debttoebitda], 'EbitdaGrowth' =>[$ebitdagrowth],  'RevenueGrowth' =>[$revenuegrowth],);

$data = json_decode(file_get_contents('Stockdata1.json'));

if (!$data) {
    // file is empty or does not contain valid JSON
    $data = [];
} elseif (is_object($data)) {
    // file only contains a JSON object, not a JSON array
    $data = [ $data ];
}

$data[] = $jsonarray;
file_put_contents('Stockdata1.json', json_encode($data));