Make first item in array appear at the last item

时间:2017-03-22 18:51:27

标签: php arrays coordinates polygon

Just to note I dont mean to reverse the whole array, just one item which is at the beginning of the array to also appear at the end of the array

I have an example of an array but i dont know how i can make mine to look the same.

I wanted to create a polygon using co-ordinate, and i found an example on the net that draws the polygon using an array. Below is the array that i found from the site

$polygon = array("-50 30","50 70","100 50","80 10","110 -10","110 -30","-20 -50","-30 -40","10 -10","-10 10","-30 -20","-50 30");

Condition is that the first and last array must be the same. And their example is from static numbers.

In my case i have dynamic list of coordinates from the database and i would wish it to generate something like the example given above.

Here is what i have tried but it does not seem to work. My code now

$query_points = mysqli_query($link,"SELECT * FROM ec"); 
$row_points = mysqli_fetch_assoc($query_points);

$query_lastpoint = mysqli_query($link,"SELECT * FROM ec"
$row_lastpoint = mysqli_fetch_assoc($query_lastpoint);

$longitude_last = $row_lastpoint['longitude'];
$latitude_last = $row_lastpoint['latitude'];
$polygon= array();
while ($row_points = mysqli_fetch_assoc($query_points))
{
    $longitude_xx = $row_points['longitude'];
    $latitude_yy = $row_points['latitude'];
    $xx_yy = ''.$longitude_xx.' '.$latitude_yy.'';
    $polygon[] = $xx_yy;

}
$polygon[] = "$longitude_last $latitude_last";

Its like from the source they use the variable directly as $polygon while mine is $polygon[]; and i cant say $polygon = $polygon[];

Any Assistance?

1 个答案:

答案 0 :(得分:4)

你可以再次追加它,如果它已经存在它就不会有所不同

$array[]=  $array[0];

否则你可以做到

if (end($array) != reset($array)) {  //add the first element here

http://php.net/manual/en/function.end.php

http://php.net/manual/en/function.reset.php