0

I have an array of coordinates that I have extracted from JSON. Only issue I have is each index has a part of each set of coordinates. If this sounds confusing let me explain further. So basically for usage on google maps you have two parts to each set of coordinates usually separated by a comma i.e. 50.192847,-0.837228 (just an example). Problem I've got is somehow the two parts have ended up in different indexes for example:

array[0] = '50.192847'
array[1] = '-0.837228'
array[2] = '53.998772'
array[3] = '2.337622'

I think you get the idea. So my question is how do I combine each pair of indexes to make up each set of coordinates? So again for example combine array[0] and array[1] together. Is there a loop that can do this or a PHP array function of some sort?

Thanks in advance for the help!

2 Answers 2

3

Split to pairs and implode with comma

$array[0] = '50.192847';
$array[1] = '-0.837228';
$array[2] = '53.998772';
$array[3] = '2.337622';

foreach (array_chunk($array, 2) as $coords)
   echo implode(',', $coords) . "\n";

result

50.192847,-0.837228
53.998772,2.337622
Sign up to request clarification or add additional context in comments.

Comments

0

You could use a loop to start at every second key.

$newArray = array();
for($i = 0; $i < count($array) - 1 && count($array) % 2 == 0; $i = $i + 2) {
    $newArray[] = $array[$i] . ',' . $array[$i + 1];
}

3 Comments

Just tried that but when I tried print_r($newArray) it's just outputting Array ( ) like there is nothing there except for an empty array. Any ideas?
Does the array contain an even number of elements? Because it works for me, so maybe you copied my code before I updated it? I forgot to check if the modulo operation returned zero in the first version. Also you need to have your array with coordinates in an array named $array or change the code.
I noticed the updated version and tried it but no it didn't work unfortunately, not sure why. I got the answer above though, thanks for your help :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.