如何使用php的push_array为二维数组添加时间戳和值

How can I use array_push to add a timestamp and a value to a two-dimensional array with square bracket syntax?

I successfully get rows, each with a timestamp and associated value from a mysql database. While retrieving the results, I add these times and values into an array like so:

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

I need the final array to contain an even number of elements (which will be within a time interval of 30 minutes), so I test for that:

If the LAST array element(s?) has a timestamp and associated value of 1, I want to append at the end of the array the ending half-hour timestamp along with a 0.

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

On the other hand, if the FIRST element(s?) has a timestamp with associated value of 1, I want to append at the beginning of the array the starting half-hour timestamp along with a 0.

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

Really would appreciate help! Thank you!

To add a new row to the end of the array, write:

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

To insert at the beginning of the array, use array_splice:

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

For your specific question:

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

This works with unix timestamp format. If using MySQL datetime you'll need to convert accordingly.