PHP将字符串分解为数组
我有一个循环,其中包含逗号分隔值的字符串。PHP将字符串分解为数组
foreach ($profiles as $profile) {
$user_states[] = exlpode(', ', '[string of comma seperated states]');
}
我遇到的问题是$user_states
阵列最终被两个级别,与回路创建嵌套阵列的每个itteration。
array (size=2)
0 =>
array (size=3)
0 => string 'DC' (length=2)
1 => string 'Maryland' (length=8)
2 => string 'Northern-Virginia' (length=17)
1 =>
array (size=1)
0 => string 'North-Carolina,Virginia' (length=23)
如何将分解值放入单个数组中?谢谢!
[]=
的操作装置添加到阵列。 explode
方法返回一个数组,所以你正在做的是向数组中添加一个数组。
因为profiles
可能包含2个元素,你正在展开串
你可能正在寻找的大小为2的数组array_merge
这种替换环的内侧部分:
$exploded = exlpode(', ', '[string of comma seperated states]');
$user_states = array_merge($user_states, $exploded)
你尝试这个
$user_states = exlpode(', ', '[string of comma seperated states]');
编辑:
如果我没看错这个代码可以帮助你
$profiles = array("yale, ny, la", "boston, vegas");
$user_states = array();
foreach ($profiles as $profile) {
$tmp = explode(', ', $profile);
$user_states = array_merge($tmp, $user_states);
}
var_dump($user_states);
你需要的是:
$user_states = array();
foreach ($profiles as $profile) {
$user_states = array_merge($user_states, exlpode(', ', '[string of comma seperated states]'));
}
个
问候, 瓦伦丁
谢谢你的答案。虽然这是正确的,但我会向迪玛提供他对状况的明确解释。 – psorensen 2014-10-26 17:30:57
使用合并功能:
$states=array();
foreach ($profiles as $profile) {
$user_states = exlpode(', ', '[string of comma seperated states]');
array_merge($states,$user_states);
}
var_dump($states);
谢谢Niko。该死的复制和粘贴;) – 2014-10-26 17:33:35
您可以尝试
$user_states = array();
...
$user_states += explode(', ', '[string of comma seperated states]');
...
这将不断增加的 '爆炸' 阵列主要$ user_states阵列。
由于我不知道$profiles
中有什么,我给你一个简单的例子。
$user_states = array();
$profiles = array('UK, FR, CA, AU', 'UK, FR, CA, AU', 'NW');
foreach ($profiles as $profile)
{
$extract = explode(', ', $profile);
$user_states = array_merge($user_states, $extract);
}
// if you want to remove duplications
$user_states = array_unique($user_states);
echo '<pre>';
print_r($user_states);
会给你:
Array
(
[0] => UK
[1] => FR
[2] => CA
[3] => AU
[8] => NW
)
和
如果不使用array_unique()
Array
(
[0] => UK
[1] => FR
[2] => CA
[3] => AU
[4] => UK
[5] => FR
[6] => CA
[7] => AU
[8] => NW
)
你的问题是,'爆炸()'返回一个数组。如果将数组作为新元素分配到目标数组'$ user_states'中,那么显然会得到一组数组。 – arkascha 2014-10-26 17:24:25
在循环之前初始化一个主数组并将其合并到(array_merge) – 2014-10-26 17:26:25