我正在为每行句子中的循环移位词编写代码。假设我输入以下两行:
输出应为:
brother merry christmas
christmas brother merry
merry christmas brother
sister happy new year
year sister happy new
new year sister happy
happy new year sister
这是我到目前为止编写的代码
function array_sort($array){
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
$sortable_array[$k] = $v2;
}
} else {
$sortable_array[$k] = $v;
}
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
foreach($str_in as $str){
$st= explode(" ",trim($str));
//print_r($st);
for($i=0;$i<count($st);$i++){
$sorted = array_sort($st);
}
}
答案 0 :(得分:4)
使用array_pop()
和array_unshift()
可以轻松实现这一目标。
$strings = [
"merry christmas brother",
"happy new year sister"
];
foreach ($strings as $string) {
$words = explode(" ", $string);
for ($i = 0; $i < count($words); $i++) {
array_unshift($words, array_pop($words));
echo implode(" ", $words), "\n";
}
echo "\n";
}
brother merry christmas
christmas brother merry
merry christmas brother
sister happy new year
year sister happy new
new year sister happy
happy new year sister