如果没有大量复杂的代码,我怎么能做到以下几点?
通过这个,我的意思是:
$array[1]=blue,green
$array[2]=yellow,red
变为
$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
我刚刚意识到,我可以用for ...每个循环吗?如果是这样,请回答是。一旦我知道从哪里开始,我就可以编码。
答案 0 :(得分:4)
鉴于此:
$array[1] = "blue,green";
$array[2] = "yellow,red";
以下是如何操作:
foreach ($array as $key => $value) {
$temp = explode(",", $value, 2); // makes sure there's only 2 parts
$array[$key] = $temp[1];
}
你能做到的另一种方式是:
foreach ($array as $key => $value) {
$array[$key] = preg_replace("/^.+?,$/", "", $value);
}
...或使用substr()
和strpos()
答案 1 :(得分:1)
试试这个:
$arr = explode(',','a,b,c');
unset($arr[0]);
虽然,实际上,你问的是没有意义的。如果你知道有两个部分,你可能想要更接近这个:
list(,$what_i_want) = explode('|','A|B',2);
答案 2 :(得分:0)
foreach ($array as $k => &$v) {
$v = (array) explode(',', $v);
$v = (!empty($v[1])) ? $v[1] : $v[0];
}
答案 3 :(得分:0)
您开始使用的数组:
$array[1] = "blue,green";
$array[2] = "yellow,red";
编码的一种方法:
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);
注意:这会创建一个与$array
不同的数组。
因此$array
== $prime
但不是 $array
=== $prime