如何使用 PHP 的push_array将时间戳和值添加到二维数组中


how to use php's push_array to add a timestamp and value to a two-dimensional array

如何使用

array_push向带有方括号语法的二维数组添加时间戳和值?

我成功地从mysql数据库中获取了行,每行都有一个时间戳和关联的值。在检索结果时,我将这些时间和值添加到一个数组中,如下所示:

while($row=mysqli_fetch_array($r, MYSQLI_ASSOC)){   
$q1_array[$i][0]= $row["time"];             
$q1_array[$i][1]= $row["val"]; // the value ("val") will either be 1 or 0 (ON or OFF)
$i++;
}

我需要最终数组包含偶数个元素(将在 30 分钟的时间间隔内),所以我对此进行了测试:

如果 LAST 数组元素的时间戳和关联的值为 1 ,我想在数组的末尾附加结束半小时的时间戳以及一个0

if ($q1_array[sizeof($q1_array)-1][1] == 1){ 
//here I want to append a timestamp and value                       
}

另一方面,如果 FIRST 元素的时间戳与关联值为 1 ,我想在数组的开头附加起始半小时时间戳以及一个0

else if ($q1_array[0][1]== 1){ 
//here I want to append a timestamp and value
}

真的会感谢帮助!谢谢!

要在数组末尾添加新行,请编写:

$new_row = array($timestamp, 0);
$q1_array[] = array($timestamp, 0);

要在数组的开头插入,请使用array_splice

array_splice($q1_array, 0, 0, $new_row);

对于您的具体问题:

//process first element
if($q1_array[0][1] == 1){
    $time = roundTime($q1_array[0][0], 'start');
    $newElement = array( $time, 0 );
    array_unshift($q1_array, $newElement);
}
//process last element
$len = count($q1_array) - 1;
if($q1_array[$len][1] == 1){
    $time = roundTime($q1_array[$len][0], 'end');
    $newElement = array( $time, 0 );
    array_push($q1_array, $newElement);
}
//rounding function
//$timeIn = unix timestamp, $direction = 'start' or 'end'
function roundTime($timeIn , $direction){
    $tUnit = 1800; //seconds in half-hour
    if ($direction == 'start'){
        $output = floor($timeIn / $tUnit) * $tUnit;
    } else {
        $output = ceil($timeIn / $tUnit) * $tUnit;
    }
    return $output;
}

这适用于 unix 时间戳格式。如果使用MySQL日期时间,则需要相应地进行转换。