开发者

Generate 2 arrays from an array

开发者 https://www.devze.com 2023-02-13 16:31 出处:网络
i have an array like this, with x-coordinate and y-coordinate forming an individual entry. $polygon = array(\"10 0\", \"20 5\", \"15 15\", \"22 15\");

i have an array like this, with x-coordinate and y-coordinate forming an individual entry.

$polygon = array("10 0", "20 5", "15 15", "22 15");

Now how can i break this array into 2 different arrays, such that all x-coordinates will fall into one array and all y-coordinates will fall into another arra开发者_如何学Goy, like this:

$x = array(10, 20, 15, 22);
$y = array(0, 5, 15, 15);


$x = $y = array();
$polygon = array("10 0", "20 5", "15 15", "22 15");
foreach ($polygon as $coor) {
    list($x[], $y[]) = explode(' ', $coor);
}

This will do the trick :)

And to combine them back:

//assuming that $x and $y have the same number of items
for ($i = 0; $i<count($x); $i++) {
    $polygon[] = $x[$i] .' ' . $y[$i];
}


Try that:

$x = array();
$y = array();
foreach($polygon as $entry){
 $splitted = explode(" ", $entry);
 //append x and y 
 $x[] = $splitted[0];
 $y[] = $splitted[1];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消