开发者

Move first word to the end

We have array with names:

array(
Robin Hood,
Little John,
Maid 开发者_如何学GoMarion,
Friar Tuck,
Will Scarlet
)

First word inside each item should be moved to the end of this item.

We should get this:

array(
Hood Robin,
John Little,
Marion Maid,
Tuck Friar,
Scarlet Will
)

How can we do this?

Its better if we use foreach()

Thanks.


If you only need to move the part before the first whitespace (setting $limit = 2 in explode() to get two parts only):

function func($n) {
        list($first, $rest) = explode(' ', $n, 2);
        return $rest . ' ' . $first;
} 
$trans = array_map('func', $names);

(Demo)

Gives:

Array
(
    [0] => Hood Robin
    [1] => John Little
    [2] => Marion Maid
    [3] => Tuck Friar
    [4] => Scarlet Will
    [5] => Fitzgerald Kennedy John
)


foreach($names as $key => $name)
{
    $splitted = explode(' ', $name, 2);
    $names[$key] = $splitted[1].' '.$splitted[0];
}


Not a particularly glamorous solution:

foreach( $person_array as $key => $value){

$reversed_person_array[]=implode(' ', array_reverse(explode(' ', $value,2)));

}


walk through you array, use explode to split the entry at ' '(space), then use array_shift to cut of and get the first element, array_push it to the end and implode the whole thing again with ' '(space).


Ha! that's great Ahmet!

I was working on something similar... got to

$first = $array[0];
array_shift($array);
array_push($array, $first);

then I refreshed the page and saw yours. Clean and neat!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜