0); $a-6ren">
gpt4 book ai didi

php - 在php中的数组内添加新的键,值(值= 1)

转载 作者:行者123 更新时间:2023-11-29 11:21:22 26 4
gpt4 key购买 nike

我遇到过包含日期格式的时间戳日期的情况。然后我想构建一个图表,显示“点击”项目的数量“每天”

//array declaration
$array1 = array("Date" => 0);
$array2 = array("Date" => 0);
$array3 = array("Date" => 0);
$array4 = array("Date" => 0);
$array5 = array("Date" => 0);
$array6 = array("Date" => 0);
$array7 = array("Date" => 0);
$array8 = array("Date" => 0);
//var_dump($array);

foreach ($_sql as $result1) {
$timestamp = $result1['timestamp'];
$itemType = $result1['itemType'];

//separate the time and date
$explodeTime = explode(" ", $timestamp);
$date = $explodeTime[0];
//$arrDate = array($date);

//var_dump($Date);

//if the item type is 1;
if($itemType == 1 ){



//check the existence
if(array_key_exists($date,$array1)){

//if exist increment the click by 1

foreach ($array1 as $key => $value) {

$array1[$key]=$value + 1;


//var_dump($array1);


}
}


//else add new record and set default value as 1
else{



//echo "Insert new Key";

//$array1 = array($date => 1);
//var_dump($array1);


//var_dump($array1);
//exit();


}
}

我想用这种格式得到我的数组结果

array(1) {
["2009-04-17"]=> 211
int(1)
}
array(1) {
["2009-04-18"]=> 1213
int(1)
}
array(1) {
["2009-04-19"]=> 1232
int(1)
}
array(1) {
["2009-04-20"]=> 32312
int(1)
}

这样我就可以获取日期的值,然后很容易将数据转换为json,然后插入到Chartjs中。

抱歉,如果我的问题不清楚,因为我刚刚开始学习 php。

最佳答案

我认为这就是您正在尝试做的事情:

//array declaration
$array = array();

foreach ($_sql as $result1) {
//separate the time and date
$dateTime = new DateTime($result1['timestamp']);
$date = $dateTime->format('Y-m-d');

//if the item type is 1;
if (1 == $result1['itemType']) {
//check the existence
if (array_key_exists($date, $array)) {
//if exist increment the click by 1
$array[$date]++;
} else {
$array[$date] = 1;
}
}
}

关于php - 在php中的数组内添加新的键,值(值= 1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38844737/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com