Reputation: 1744
I have an array of planets and their longitude:
$planets['Sun']['longitude']=9
$planets['Moon']['longitude']=341
$planets['Mercury']['longitude']=27
$planets['Venus']['longitude']=349
And I have an array of planetary zones called "houses", each with a longitude to divide a 360 circle into 12 unequal "houses". The longitude number represents the starting border of that zone.
$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
I want to create a function to return the house of a particular planet based on the planet's longitude. So for instance, if the planet has a longitude of 170 then it will be in house 2, because it's greater than the house 2 longitude and smaller than the house 3 longitude as shown in the above array.
I've got the following function to get a planet's house based on it's longitude. From the example above, it works fine with the Moon and Mercury, but doesn't work with the Sun and Venus. This is because the next house is smaller than the previous one, because it's the end of the 360 circle.
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;
}
So if i do: get_planet_house($houses,$planets['Moon']['longitude'])
it returns 7. But if I do the same for $planets['Sun']['longitude']
it will return blank.
How can I modify the function to work with the circle so I can get the Sun and Venus to show that they are in the 8th house?
Upvotes: 1
Views: 55
Reputation: 5186
I would sort the array and then it is a very easy task. This solution works for Sun, Moon, Venus and all other planets:
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;
}
Upvotes: 1
Reputation: 10070
If your $houses
can not be sorted for some reason, you can just add a little bit complexity to your logic:
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;
}
If left bound is smaller than right bound, then you check if the input longitude falls between these two bounds; If left bound is bigger than right bound, then you check if the input longitude falls outside these two bounds.
Upvotes: 0