将项添加到PHP数组中


Add item to PHP array

这可能是一个愚蠢而简单的问题,但我患有脑衰退。。。我使用SELECT语句从MySQL数据库中提取数据,然后使用WHILE循环将返回的数据推送到数组"$arr",使用下面的代码;

$query="SELECT idBaptism as id, baptismDate as eventDate, concat(baptismForename,' ',baptismSurname) as name, churchName, tbLocation.idLocation as locationid, location, clat as lat, clng as lng FROM tbBaptism, tbLocation, tbChurch WHERE tbBaptism.idLocation=tbLocation.idLocation AND tbBaptism.idChurch=tbChurch.idChurch";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$arr = array();
if($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $arr[] = $row;
    }
}

我的问题是,我想把文本"Baptism"附加到数组的每一行的末尾,最简单的方法是什么??

举个例子,这里是使用print_r从上面的代码生成的数组的两行的示例输出;

  Array ( [0] => Array ( [id] => 1 [eventDate] => 1874-03-08 [name] => Henry Stanley [churchName] => St. Leonards [locationid] => 28 [location] => Halwell, Devon, UK [lat] => 50.366001 [lng] => -3.720500 ) 
[1] => Array ( [id] => 2 [eventDate] => 1870-11-06 [name] => Valentine Joles [churchName] => St. John The Evangelist [locationid] => 27 [location] => East Horrington, Somerset, UK [lat] => 51.218143 [lng] => -2.600683 )

我想在每行的末尾添加值对,例如[type]=>"Baptism"。。。

只需将新元素推送到提取的数组$row,然后将其推送到数组$arr,如下所示:

// your code
$arr = array();
if($result->num_rows > 0) {
    while($row = $result->fetch_assoc()){
        $row['type'] = 'Baptism';
        $arr[] = $row;
    }
}