PHP将字符串爆炸成数组

时间:2014-10-26 17:20:19

标签: php arrays explode

我有一个包含逗号分隔值字符串的循环。

foreach ($profiles as $profile) {
  $user_states[] = exlpode(', ', '[string of comma seperated states]');
}

我遇到的问题是$user_states数组最终是两个级别,循环的每次迭代都会创建一个嵌套数组。

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)

如何获取爆炸值并将它们全部放入单个数组中?谢谢!

6 个答案:

答案 0 :(得分:2)

[]=运算符意味着添加到数组。 explode方法,返回一个数组,所以你要做的就是在数组中添加一个数组。

由于profiles可能包含2个元素,因此您将获得一个大小为2的爆炸字符串数组

您可能正在寻找的是array_merge

用这个替换循环的内部部分:

$exploded    = exlpode(', ', '[string of comma seperated states]');
$user_states = array_merge($user_states, $exploded)

答案 1 :(得分:1)

你试过这个吗?

$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);

答案 2 :(得分:1)

您需要的是:

$user_states = array();
foreach ($profiles as $profile) {
  $user_states = array_merge($user_states, exlpode(', ', '[string of comma seperated states]'));
}

此致 的Valentin

答案 3 :(得分:1)

使用合并功能:

$states=array();

foreach ($profiles as $profile) {
    $user_states = exlpode(', ', '[string of comma seperated states]');
    array_merge($states,$user_states);
}

var_dump($states);

答案 4 :(得分:1)

你可以尝试

$user_states = array();
...
$user_states += explode(', ', '[string of comma seperated states]');
...

这将继续将'explode'数组添加到主$ user_states数组中。

答案 5 :(得分:1)

由于我不知道$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
)