質問

I have two strings containing values separated by comma and space.

Example: String 1 = France, Germany, Italy; String 2 = Belgium, Netherlands What I want is create an array in PHP that contains all values from both strings and sorted alphabetically. So in this case the output should be an array with the following values and order: Belgium,France,Germany,Italy,Netherlands.

I tried the following but this doesnt work. Can anyone tell me how I can achieve this ? I saw that I need to explode the single strings first as otherwise it seems to treat all values from one string as just one value and then the sorting doesnt work.

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

Many thanks for any help with this, Mike.

役に立ちましたか?

解決

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

Check the string => "France","Germany","Italy" != "France, Germany, Italy"

他のヒント

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

sort($countries);

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

Or join the strings 1st

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

$countries = explode(",", $input1 . "," . $input2);
sort($countries);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top