在PHP中将字符添加到项目数组前面

3
我正在尝试将字符串... php,mysql,css 转换为... #php #mysql #css

What I have so far...

$hashTagStr  = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);

foreach($hashTags as $k => $v){
    $hashTagsStr = '';
    $hashTagsStr .= '#'.$v.' ';
}
echo $hashTagsStr;

?>

Problem is it only prints #css

8个回答

9
这个怎么样:
$hashTagStr  = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
$hashTagStr = '#' . implode( ' #', $hashTags );

...或者:

$hashTagStr  = "php,mysql,css";
$hashTagStr = '#' . str_replace( ',', ' #', $hashTagStr );

6
那是因为每次循环运行时,您都会通过以下方式清除$hashTagsStr:
$hashTagsStr = '';

将其更改为:

$hashTagStr  = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
$hashTagsStr = '';
foreach($hashTags as $k => $v){
    $hashTagsStr .= '#'.$v.' ';
}
echo $hashTagsStr;

4

通过引用传递值:

$hashTags = array("php","mysql","css");

foreach ( $hashTags as &$v ) $v = "#" . $v;

然后彻底整理结果:
// #php #mysql #css
echo implode( " ", $hashTags );

演示: http://codepad.org/zbtLF5Pk

让我们来看看你正在做什么:

// You start with a string, all good.
$hashTagStr = "php,mysql,css";

// Blow it apart into an array - awesome!
$hashTags = explode( "," , $hashTagStr );

// Yeah, let's cycle this badboy!
foreach($hashTags as $k => $v) {

    // Iteration 1: Yeah, empty strings!
    // Iteration 2: Yeah, empty...wait, OMG!
    $hashTagsStr = '';

    // Concat onto an empty var
    $hashTagsStr .= '#'.$v.' ';
}

// Show our final output
echo $hashTagsStr;

3
看起来需要使用 array_walk 函数。
$hashTagStr  = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);
array_walk($hashTags, function(&$value){ $value = "#" . $value ;} );
var_dump(implode(" ", $hashTags));

输出

 string '#php #mysql #css' (length=16)

1
哦,我也想回答这个问题 :-)。 - Zombaya
2
你也可以使用 array_map$hashTags = array_map(function($a){return "#$a";}, $hashTags); :-P - gen_Eric

2
你应该将$hashTagsStr = ''移出foreach循环,否则每次都会重置它。

1

您正在循环内定义变量$hashTagsStr

<?php

$hashTagStr  = "php,mysql,css";
$hashTags = explode(",", $hashTagStr);

$hashTagsStr = '';
foreach($hashTags as $k => $v){
    $hashTagsStr .= '#'.$v.' ';
}
echo $hashTagsStr;

无论如何,我认为这会更简单:

<?php

$hashTagStr  = "php,mysql,css";
$hashTagStr = '#' . str_replace(',', ' #', $hashTagStr);

echo $hashTagStr;

1

在循环的每个迭代中,您都会执行$hashTagsStr = '';。这将变量设置为'',然后附加当前标记。因此,完成时,$hashTagsStr仅包含最后一个标记。

此外,在这里使用循环似乎太麻烦了,您可以更轻松地用#替换,。无需将其拆分为数组,也无需循环。尝试这个:

$hashTagStr  = "php,mysql,css";
$hashTagStr = '#'.str_replace(',', ' #', $hashTagStr);

0
function prepend( $pre, $array )
{
    return array_map(
        function($t) use ($pre) { return $pre.$t; }, $array
    );
}

你在字符串中所拥有的语义是一个数组。➪ 所以最好尽早分解,并尽可能长时间地使用你的数组。

闭包和匿名函数如所示,适用于PHP 5.4+。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接