在一行中对数组项执行函数

时间:2013-07-20 14:38:48

标签: php arrays

<?php
$fruits = "lemon
    orange
banana
apple
    pear";

$fruits_a = explode("\n", $fruits);
for ($i = 0; $i < count($fruits_a); $i++)
{
    $fruits_a[$i] = trim($fruits_a[$i]);
}
$fruits = implode(" ", $fruits_a);

echo $fruits;
?>

是否可以将此(从爆炸变为内爆)转换为单行? 在python中它只是fruits = " ".join(x.strip() for x in fruits.split("\n"))

2 个答案:

答案 0 :(得分:2)

$fruits = implode(
    ' ',
    array_map(
        'trim',
        explode("\n", $fruits)
    )
);

答案 1 :(得分:1)

是的

$fruits = implode(' ', array_map('trim', explode('\n', $fruits)));