PHP:爆炸两个字符串并放在排序数组中

时间:2014-04-30 21:41:43

标签: php arrays sorting loops foreach

我有两个包含以逗号和空格分隔的值的字符串。

示例:字符串1 =法国,德国,意大利;字符串2 =比利时,荷兰 我想要的是在PHP中创建一个包含两个字符串的所有值并按字母顺序排序的数组。 所以在这种情况下,输出应该是一个具有以下值和顺序的数组: 的比利时,法国,德国,意大利,荷兰

我尝试了以下但这不起作用。谁能告诉我如何实现这一目标?我看到我需要首先爆炸单个字符串,否则它似乎将一个字符串中的所有值视为一个值,然后排序不起作用。

$countries = array();
$input1 = explode(", ", "France", "Germany", "Italy"); //hard-coded for testing
$input2 = explode(", ", "Belgium", "Netherlands"); //hard-coded for testing
foreach($input1 as $key => $val) {
    array_push($countries, $input1);
}
foreach($input2 as $key => $val) {
    array_push($countries, $input2);
}
sort($countries);

非常感谢Mike的任何帮助。

3 个答案:

答案 0 :(得分:1)

foreach ($input2 as $input){
  $countries[]=$input;
}

sort($countries);

答案 1 :(得分:1)

$input1 = explode(", ", "France, Germany, Italy"); 
$input2 = explode(", ", "Belgium, Netherlands"); 
$countries = array_merge($input1, input2);
var_dump(sort($countries));

检查字符串=> "France","Germany","Italy" != "France, Germany, Italy"

答案 2 :(得分:1)

使用array_merge

$input1 = explode(",", "France,Germany,Italy"); //hard-coded for testing
$input2 = explode(",", "Belgium,Netherlands"); //hard-coded for testing

$countries = array_merge($input1, $input2)
sort($countries);

或加入字符串1st

$input1 = "France,Germany,Italy"; 
$input2 = "Belgium,Netherlands";

$countries = explode(",", $input1 . "," . $input2);
sort($countries);