skip to Main Content

The following array contains a list of coordinates that I’m using to draw a polygon with ImageMagick:

$points = [
    ['x' => 40, 'y' => 10],
    ['x' => 20, 'y' => 20],
    ['x' => 70, 'y' => 50],
    ['x' => 60, 'y' => 15],
];

What I want to do is loop through this array and calculate the mid-point of each polyline by comparing each consecutive pair of coordinates including the first and last set i.e. the check must wrap-around either at the start or end of the loop. Is there a way to do this programatically without a lot of kludgey code to count the number of elements in the array and if() tests to determine when the first or last element has been reached, etc.?

2

Answers


  1. Is this what you’re after? Updated

    $points = [
        ['x' => 40, 'y' => 10],
        ['x' => 20, 'y' => 20],
        ['x' => 70, 'y' => 50],
        ['x' => 60, 'y' => 15],
    ];
    
    $mids = [];
    
    foreach (array_values($points) as $k => $v) {
        if (!empty($points[$k+1])) {
            $x1 = $points[$k]['x'];
            $x2 = $points[$k+1]['x'];
            $y1 = $points[$k]['y'];
            $y2 = $points[$k+1]['y'];
            $mids[] = ['x' => ($x1 + $x2) / 2, 'y' => ($y1 + $y2) / 2];
        }
    }
    
    print_r($mids);
    

    output of this is

    Array
    (
        [0] => Array
            (
                [x] => 30
                [y] => 15
            )
    
        [1] => Array
            (
                [x] => 45
                [y] => 35
            )
    
        [2] => Array
            (
                [x] => 65
                [y] => 32.5
            )
    
    )
    
    Login or Signup to reply.
  2. Use modulus to wrap around to 0 at the end.

    $midpoints = [];
    $len = count($points);
    foreach ($points as $i => $point1) {
        $point2 = $points[($i+1) % $len];
        $midpoints[] = get_midpoint($point1, $point2);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search