Search code examples
phparraysgeojson

combine two arrays by key position


I'm trying to create geoJson out from this:

(48.178, 16.410),(48.175, 16.408),(48.174, 16.414),(48.176, 16.415)

After I created an array I split it with preg_grep in two:

Array ( [1] => 16.410 [3] => 16.408 [5] => 16.414 [7] => 16.415 ) 

Array ( [0] => 48.178 [2] => 48.175 [4] => 48.174 [6] => 48.176 ) 

What I want to do actually, is to exchange latitude an longitude.

How can I combine these arrays by key position? the result should be

Array ( [1] => 16.410 [0] => 48.178 [3] => 16.408 [2] => 48.175 ......... ) 

Solution

  • You can do ordinary loop with step by 2 and build new array:

    $out = array();
    $count = count($src);
    for($i=0; $i<$count; $i+=2) {
        $out[] = $src[$i];
        $out[] = $src[$i+1];
    }
    

    Note that if you want keys preserved then you shouldn't use numeric keys, but i.e. strings instead. And, in fact, you should consider building multidimensional array instead:

        $out[] = array($src[$i], $src[$i+1]);
    

    as by logic this data are paired.