更新的问题。我如何在数组中添加其他列。我想添加一列距离,这是我创建的公式的结果
这是我的代码
$db = $this->getDbo();
$query = $db->getQuery(true)
->select('*')
->from('#__listing');
$db->setQuery($query);
$db->query();
$rows = $db->loadRowList();
$arr_data = array();
foreach ($rows as $row) {
$theta = $longitudeFrom - $row->longitude;
$dist = sin(deg2rad($latitudeFrom))
* sin(deg2rad($row>latitude))
+ cos(deg2rad($latitudeFrom))
* cos(deg2rad($row->latitude))
* cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$distance = $miles * 1.609344;
$key = $row[0];
$arr_data[$key] = array('id' => $row[0], 'name' => $row[1]);
}
这是我尝试过的
$arr_data = array();
foreach ($rows as $row) {
$theta = $longitudeFrom - $row->longitude;
$dist = sin(deg2rad($latitudeFrom))
* sin(deg2rad($row>latitude))
+ cos(deg2rad($latitudeFrom))
* cos(deg2rad($row->latitude))
* cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$distance = $miles * 1.609344;
$key = $row[0];
$arr_data[$key] = array(
'id' => $row[0],
'name' => $row[1],
'distance' => $distance);
}
答案 0 :(得分:1)
我是否正确理解您想获取一个新数组,其中包含$ rows中每个记录的汇总记录?如果是,则可以执行以下操作:
This module can only be referenced with ECMAScript imports/exports by turning on the 'esModuleInterop' flag and referencing its default export.ts(2497)
PS::我使用的是简写数组表示法$db = $this->getDbo();
$query = $db->getQuery(true)
->select('*')
->from('#__listing');
$db->setQuery($query);
$db->query();
$rows = $db->loadAssocList();
$arr_data = [];
foreach ($rows as $rowIndex=>$rowData) {
$theta = $longitudeFrom - $rowData['longitude'];
$dist = sin(deg2rad($latitudeFrom))
* sin(deg2rad($rowData['latitude']))
+ cos(deg2rad($latitudeFrom))
* cos(deg2rad($rowData['latitude']))
* cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$distance = $miles * 1.609344;
$arr_data[$rowIndex] = [
'id' => $rowData['id'],
'name' => $rowData['name'],
'distance' => $distance
];
}
,但它等于[]
PPS:在原始代码中还存在一个问题,将array()
变量视为对象$row
,而不是数组$row->longitude
。哪一个是正确的取决于您如何获得$row[1]
,但无论如何都不要混淆。
PPPS:以下是我的评论,我已经使用loadAssocList更新了答案以获取关联数组并进行了更改
$rows
到
'id' => $rowData[0],
'name' => $rowData[1],
假定您的“ id”和“ name”字段分别在数据库中命名。