Json以错误的格式编码

问题描述 投票:2回答:2

我正在尝试对我网站上的访问进行一些统计。我知道我可以使用谷歌分析(我做),但我想尝试自己做一些事情,这是一个学习它的好方法。

问题:我在我的数据库中选择日期并对它们进行排序以适应本周。之后,我想将它们添加到json文件中。 CanvasJS使用该json文件制作图表。我尝试了一些不同的方法,只是为了让它顺利工作。但是json数组的格式不是CanvasJS想要的。

我需要的:

{ visits:[[2019-02-12, 49,],[2019-02-13,40,],[2019-02-14,46,],[2019-02-15,37,], [2019-02-16,31,],[2019-02-17,38,],[2019-02-18,4,] }

我得到了什么:

{ "visits":{"2019-02-12":49,"2019-02-13":40,"2019-02-14":46,"2019-02-15":37,"2019-02-16":31,"2019-02-17":38,"2019-02-18":4} }

我的PHP脚本:

// Get first and last day of the current week
$first_day = date('Y-m-d', strtotime("- 6 days"));
$last_day = date('Y-m-d', strtotime("+ 1 days "));

// Return all results the past 7 days
$sql = "SELECT date FROM table WHERE date >= '" . $first_day . "' AND date < '" . $last_day . "'";
if($result = $conn->query($sql)){

    $response = array(); 
    $visits = array();

    while($row = $result->fetch_array(MYSQLI_ASSOC)){

        $old_date = $row['date'];
        $old_date_timestamp = strtotime($old_date);
        $new_date = date('Y-m-d', $old_date_timestamp);

                // I dont need the keys, but I cant avoid it to
                // get it to work....
        $visits[] = array(
            'date' => $new_date
        );

    }

    // Add sum of Dates
    $response['visits'] = array_count_values(array_column($visits, 'date'));

    // Save to json File
    $fp = fopen('results.json', 'w');
    fwrite($fp, json_encode($response));
    fclose($fp);
}
$conn->close();

感谢任何能够提供帮助的人。

php arrays json encode
2个回答
1
投票

忽略任何引用相关的问题你可能认为是问题(但不是),看来你的主要区别在于你想要的......

[[2019-02-12, 49,],...

你有什么......

{"2019-02-12":49,...

这是因为array_count_values()创建了一个关联数组,并将日期作为键。

通过将数据库分组并计数而不是在PHP中进行操作,可以大大简化您的问题。您还可以使用预先准备的声明而不是直接值注入。

// Get first and last day of the current week
$first_day = date('Y-m-d', strtotime("- 6 days"));
$last_day = date('Y-m-d', strtotime("+ 1 days "));

$sql = <<<_SQL
SELECT DATE(`date`), COUNT(1)
FROM `table` WHERE `date` BETWEEN ? AND ?
GROUP BY DATE(`date`)
_SQL;

$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $first_day, $last_day);
$stmt->execute();
$stmt->bind_result($date, $count);
while ($stmt->fetch()) {
    $visits[] = [$date, $count];
}
$response = [ 'visits' => $visits ];

// Save to json File
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);

0
投票

我理解的是,如果我正确理解这里是一个解决方案,你想要将数组与访问中的数组相同。

在将其更改为json字符串之前,添加一个用于更多循环以生成格式php数组。

$first_day = date('Y-m-d', strtotime('- 6 days'));
$last_day = date('Y-m-d', strtotime('+ 1 days '));

$sql = "SELECT date FROM table WHERE date >= '" . $first_day . "' AND date < '" . $last_day . "'";
if ($result = $conn->query($sql)) {
    $response = [];
    $visits = [];

    while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
        $old_date = $row['date'];
        $old_date_timestamp = strtotime($old_date);
        $new_date = date('Y-m-d', $old_date_timestamp);

        $visits[] = [
        'date' => $new_date
    ];
    }

    // here the change start
    $format = [];
    foreach ($visits as $visit) {
        $format[$visit['date']][] = $visit['date'];
    }
    $response['visits'] = array_values($format);
    // here the change end

    $fp = fopen('results.json', 'w');
    fwrite($fp, json_encode($response));
    fclose($fp);
}
$conn->close();

如果你不需要密钥date这里另一个解决方案

$first_day = date('Y-m-d', strtotime('- 6 days'));
$last_day = date('Y-m-d', strtotime('+ 1 days '));

$sql = "SELECT date FROM table WHERE date >= '" . $first_day . "' AND date < '" . $last_day . "'";
if ($result = $conn->query($sql)) {
    $response = [];
    $visits = [];

    while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
        $old_date = $row['date'];
        $old_date_timestamp = strtotime($old_date);
        $new_date = date('Y-m-d', $old_date_timestamp);

        $visits[$new_date][] = $new_date; // change here
    }

    $response['visits'] = array_values($visits); // change here

    $fp = fopen('results.json', 'w');
    fwrite($fp, json_encode($response));
    fclose($fp);
}
$conn->close();

说明

在PHP中有两种类型的索引和关联数组,当你将PHP数组改为json字符串时,索引数组变为数组,关联变为对象。

$indexed = [
    0 => 'foo',
    1 => 'bar'
];

$associative = [
    'one' => 'foo',
    'two' => 'bar'
];

var_dump(json_encode($indexed));
// [
//   "foo",
//   "bar"
// ]

var_dump(json_encode($associative));
// {
//   one: "foo",
//   two: "bar"
// }

在我的代码中我使用访问日期作为键,这样同一个日期将进入相同的数组,我array_values将关联转换为索引

© www.soinside.com 2019 - 2024. All rights reserved.