我想将所有以空格开头的字符串添加到另一个字符串中。
<?php
$array = array(
"1" => "android",
"2" => "apple",
"3" => " iphone 6",
"4" => " iphone 5",
"5" => " iphone",
"6" => "blackberry",);
$phone = [];
foreach ($array as $value) {
if (substr($value, 0, 1)==' ') {
$apple = (end($phone));
$string = [$apple = $apple.$value];
} else {
$phone[] = $value;
}
}
?>
如果我尝试将字符串放在一起,我会得到三根字符串而不是一根。
var_dump ($apple=$apple.$value);
'apple iphone 6 iphone 6'
'apple iphone 5 iphone 5'
'apple iphone iphone'
但我想有这样的字符串。
'apple iphone 6 iphone 5 iphone'
如果可以,您可能应该将数据数组更改为这样的数组。
<?php
$array = [
"android",
"apple" => [
"iphone 6",
"iphone 5",
"iphone",
],
"blackberry",
];
$phones = [];
foreach ($array as $key => $value) {
if(is_array($value)) {
$phones[] = $key . ' ' . join(' ', $value);
} else {
$phones[] = $value;
}
}
foreach ($phones as $phone) {
echo $phone."n";
}
例: http://sandbox.onlinephpfunctions.com/code/470506a86804886345d233c373ac834e43ef818d
对这种事情使用嵌套数组更有意义。我看不出您正在使用这些键,所以我不会像您那样添加它们,并且会坚持使用普通数组。
我想我理解它,这是在数组中添加(在本例中(任何以空格开头的条目的情况。
这看起来很彻底的数组,每次它找到一个空格时,它都会将条目添加到构建字符串的末尾。 然后,当没有空格时,它将检查是否有任何添加并将其添加到输出值($list
(中,并将输出重置为文本。
$array = array(
"1" => "android",
"2" => "apple",
"3" => " iphone 6",
"4" => " iphone 5",
"5" => " iphone",
"6" => "blackberry",
"7" => " Curve"
);
$list = [];
$out = "";
$added = false;
foreach ($array as $value) {
if (substr($value, 0, 1) == ' ') {
$out .= $value;
$added = true;
}
else {
if( $added ) {
$list[] = $out;
}
$out = $value;
$added = false;
}
}
if( $added ) {
$list[] = $out;
}
print_r( $list );
这输出(注意我添加了一个曲线 - 手机坐在我的办公桌ATM上:-/(...
Array
(
[0] => apple iphone 6 iphone 5 iphone
[1] => blackberry Curve
)
我稍微修改了你的代码(实际上我删除了 2 行并添加了 1 行(。您可以通过以下方式获得所需的结果:
$array = array(
"1" => "android",
"2" => "apple",
"3" => " iphone 6",
"4" => " iphone 5",
"5" => " iphone",
"6" => "blackberry",);
$phone = [];
foreach ($array as $value) {
if (substr($value, 0, 1)==' ') {
$phone[count($phone)-1] .= $value;
} else {
$phone[] = $value;
}
}
print_r($phone);
我用了这个
$phone[count($phone)-1] .= $value;
而不是这个
$apple = (end($phone));
$string = [$apple = $apple.$value];
你可以像下面一样使用join()
。
<?php
$array = array(
"1" => "android",
"2" => "apple",
"3" => " iphone 5",
"4" => " iphone 6",
"5" => " iphone",
"6" => "blackberry",
);
$stringList = array();
foreach($array as $value) {
if(substr($value,0,1)==" ") {
array_push($stringList,$value);
}else{
// do something else
}
}
$string = join("",$stringList);
var_dump($string);