开发者

Exploding Arrays in PHP While Keeping the Original Key

How can I do the following without lots of complicated code?

  1. Explode each value of an array in PHP (I sort of know how to do this step)
  2. Discard the first part
  3. Keep the original key for the second part (I know there will be only two parts)

By this, I mean the following:

$array[1]=blue,green
开发者_Go百科$array[2]=yellow,red

becomes

$array[1]=green //it exploded [1] into blue and green and discarded blue
$array[2]=red // it exploded [2] into yellow and red and discarded yellow

I just realized, could I do this with a for...each loop? If so, just reply yes. I can code it once I know where to start.


given this:

$array[1] = "blue,green";
$array[2] = "yellow,red";

Here's how to do it:

foreach ($array as $key => $value) {
    $temp = explode(",", $value, 2);  // makes sure there's only 2 parts
    $array[$key] = $temp[1];
}

Another way you could do it would be like this:

foreach ($array as $key => $value) {
    $array[$key] = preg_replace("/^.+?,$/", "", $value);
}

... or use a combination of substr() and strpos()


Try this:

$arr = explode(',','a,b,c');
unset($arr[0]);

Although, really, what you're asking doesn't make sense. If you know there are two parts, you probably want something closer to this:

list(,$what_i_want) = explode('|','A|B',2);


foreach ($array as $k => &$v) {
    $v = (array) explode(',', $v);
    $v = (!empty($v[1])) ? $v[1] : $v[0];
}


The array you start with:

$array[1] = "blue,green";
$array[2] = "yellow,red";

One way of coding it:

function reduction($values)
{
    // Assumes the last part is what you want (regardless of how many you have.)
    return array_pop(explode(",", $values));
}

$prime = array_map('reduction', $array);

Note: This creates a different array than $array.

Therefore $array == $prime but is not $array === $prime

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜