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

时间:2016-08-09 07:36:01

标签: php mysql

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

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

所以我可以获得date的值,然后很容易将数据转换为json,然后插入Chartjs。

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

2 个答案:

答案 0 :(得分:1)

我认为这就是你要做的事情:

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

答案 1 :(得分:0)

你到底需要什么? 如果您需要将时间戳转换为日期,请使用格式化功能。

$timestamp=$result1['timestamp'];
$timestamp=new DateTime($timestamp);
$date=$timestamp->format("n.j.Y");