Php 如何在数组中循环时找到圆中的区域

Php 如何在数组中循环时找到圆中的区域,php,geometry,computational-geometry,Php,Geometry,Computational Geometry,我有一系列行星和它们的经度: $planets['Sun']['longitude']=9 $planets['Moon']['longitude']=341 $planets['Mercury']['longitude']=27 $planets['Venus']['longitude']=349 我有一系列的行星区域称为“房屋”,每个区域的经度将一个360度的圆圈分成12个不相等的“房屋”。经度数字表示该区域的起始边界 $houses[1]['longitude']=144 $houses

我有一系列行星和它们的经度:

$planets['Sun']['longitude']=9
$planets['Moon']['longitude']=341
$planets['Mercury']['longitude']=27
$planets['Venus']['longitude']=349
我有一系列的行星区域称为“房屋”,每个区域的经度将一个360度的圆圈分成12个不相等的“房屋”。经度数字表示该区域的起始边界

$houses[1]['longitude']=144
$houses[2]['longitude']=164
$houses[3]['longitude']=190
$houses[4]['longitude']=223
$houses[5]['longitude']=261
$houses[6]['longitude']=296
$houses[7]['longitude']=324
$houses[8]['longitude']=344
$houses[9]['longitude']=10
$houses[10]['longitude']=43
$houses[11]['longitude']=81
$houses[12]['longitude']=116
我想创建一个函数,根据行星的经度返回特定行星的房子。例如,如果行星的经度为170,那么它将位于第二宫,因为它大于第二宫的经度,小于第三宫的经度,如上面的数组所示

我有下面的函数,根据经度得到行星的房子。从上面的例子来看,它对月亮和水星很有效,但对太阳和金星不起作用。这是因为下一个房子比上一个小,因为它是360度圆的终点

function get_planet_house($houses,$in_long){
    for ($i=1;$i<12;$i++){
        if ($i<11){
            $next_long=$houses[$i+1]['longitude'];
        }
        else {
            $next_long=$houses[1]['longitude'];
        }
        if ($in_long>$houses[$i]['longitude']){
            if ($in_long<$next_long){
                $house=$i;
            }
        }
    }
    return $house;
}
函数get_planet_house($houses,$in_long){

对于($i=1;$i我会对阵列进行排序,然后这是一项非常简单的任务。此解决方案适用于太阳、月亮、金星和所有其他行星:

function get_planet_house( $houses, $in_long )
{
    asort( $houses );
    foreach ( array_keys( $houses ) as $key )
    {
        if ( $in_long < $houses [$key]["longitude"] )
        {
            return $key - 1;
        }
    }
    return $key;
}
函数get_planet_house($houses,$in_long)
{
asort(房屋);
foreach(数组_键($house)作为$key)
{
如果($in_long<$houses[$key][“经度”])
{
返回$key-1;
}
}
返回$key;
}

如果您的
$house
由于某种原因无法排序,您只需在逻辑上增加一点复杂性即可:

function get_planet_house(array $houses,$in_long)
{
    for($i=1;$i<=12;$i++)
    {
        $left=$houses[$i]["longitude"];
        $right=($i==12?$houses[1]["longitude"]:$houses[$i+1]["longitude"]);
        if(($left<=$right && $in_long>=$left && $in_long<$right) || ($left>$right && ($in_long>=$left || $in_long<$right)))
        {
            return $i;
        }
    }
    return 0;
}
函数get_planet_house(数组$house,$in_long)
{

对于($i=1;$i=$left | | |$in| longThanks对于答案,我的实际数组是多维的,这使事情更加复杂,我认为,因为当我使用此代码时,它显示了错误的房屋。@dlofrodloh哪个行星没有显示正确的房屋?我检查了它,它工作了。请提供行星,我将对其进行排序。我认为我的函数是非常简短和优雅。@AlBundy OP在生产代码中的实际数组很可能比所讨论的更复杂,并且他/她可能有其他业务逻辑,这些逻辑依赖于或影响
$house
的顺序,因此在实际代码中对其进行排序可能是可以接受的,也可能是不可以接受的。这就是为什么我首先避免排序的原因。@dlofrodloh但你可以既然
asort()
只在函数
get\u planet\u house()
中,并且它不会影响“global”变量,那么您甚至可以重命名它。