大家好,我有两个看起来像这样的阵列:
array(3) {
["15PCW"]=>
array(4) {
["longitude"]=>
string(17) "-88.3511517556820"
["latitude"]=>
string(16) "35.9298720640290"
["knownLocationTag"]=>
string(7) "15PCW"
["count"]=>
string(1) "0"
}
["12RCD"]=>
array(4) {
["longitude"]=>
string(17) "-88.4423244521810"
["latitude"]=>
string(16) "34.0964334531290"
["knownLocationTag"]=>
string(6) "12RCD"
["count"]=>
string(1) "0"
}
["43RICK"]=>
array(4) {
["longitude"]=>
string(17) "-88.5154700586220"
["latitude"]=>
string(16) "34.0726750453080"
["knownLocationTag"]=>
string(11) "43RICK"
["count"]=>
string(1) "0"
}
}
array(3) {
[12]=>
array(4) {
["entryID"]=>
string(2) "12"
["longitude"]=>
string(17) "-88.35108453430"
["latitude"]=>
string(16) "32.9298345948310"
["knownLocationTag"]=>
NULL
}
[13]=>
array(4) {
["entryID"]=>
string(2) "13"
["longitude"]=>
string(17) "-88.3513437005120"
["latitude"]=>
string(16) "32.9458453856350"
["knownLocationTag"]=>
NULL
}
[14]=>
array(4) {
["entryID"]=>
string(2) "14"
["longitude"]=>
string(17) "-88.3511544967700"
["latitude"]=>
string(16) "32.9293468765800"
["knownLocationTag"]=>
NULL
}
}
我想使用PHP迭代每个第二组数组并运行一个函数,包括来自两个数组的数据(在这种情况下,我们检查两个GPS位置之间的距离),如果它们在x英里的范围内第一个数组中列表中的项目增加“计数”值,或者如果它们超出该设置范围,则将该值添加到第一个数组中。
到目前为止,我的解决方案只是4个嵌套的foreach循环,它变得很乱。这是正确的方法还是有更好的方法?
foreach ($devices as $devicesKey => $devicesValue)
{
foreach ($devicesValue as $devicesKey2 => $devicesValue2)
{
$testarray[$devicesKey2] = $devicesValue2;
}
foreach ($locations as $locationsKey => $locationsValue)
{
foreach ($locationsValue as $locationsKey2 => $locationsValue2)
{
$testarray2[$locationsKey2] = $locationsValue2;
}
}
$test = distance($testarray['longitude'],$testarray['latitude'],$testarray2['longitude'],$testarray2['latitude']);
if ($test < .26)
{
//we would incriment the counter here since we match
}
else
{
//we would add the value to the array here since we are outside the bounds
}
}
答案 0 :(得分:0)
看起来很乱,它可能是正确的方法。您可以通过创建evaluateDevice
函数来清理代码,对于第二个列表中的每个元素,您将其传递给函数,该函数负责根据您的第一个列表处理它
foreach($devices as $key => $outerDevice){
foreach($outerDevice as $device){
evaluateDevice($outerDevice, $device, $key);
}
}
function evaluateDevice(array $outerDevice, array $device, $key)
{
foreach($locations as $outerLocation){
foreach($OuterLocation as $location){
$distance = distance($device['longitude'], $device['latitude'], $location['longitude'], $location['latitude']);
if($distance < .26){
// increment count
}else{
// remove from second list and add to first
$locations['12ABC"] = $device;
unset($outerDevice[$key]);
}
}
}
}