循环移位PHP中的一行句子中的单词

时间:2014-12-24 05:50:33

标签: php arrays

我正在为每行句子中的循环移位词编写代码。假设我输入以下两行:

  • 圣诞快乐的兄弟
  • 新年快乐的妹妹

输出应为:

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

}

}

1 个答案:

答案 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