将项添加到PHP数组

时间:2016-04-30 06:59:59

标签: php arrays

这可能是一个非常简单的问题,但我正在遭受脑力衰退...我正在使用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] => '洗礼'......

1 个答案:

答案 0 :(得分:0)

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

// your code

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