在PHP中组合子字符串

时间:2018-10-21 15:21:32

标签: php arrays substr

我想将所有以空格开头的字符串添加到另一个字符串中。

<?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'

4 个答案:

答案 0 :(得分:1)

如果可以的话,您可能应该将数据数组更改为如下所示。

<?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

对这种事情使用嵌套数组更有意义。我看不到您正在使用这些键,因此我不会像现有的那样添加它们,并且会坚持使用普通的数组。

答案 1 :(得分:0)

我想我理解,在这种情况下,是在数组中的条目之前添加一个以空格开头的条目(在本例中)。

这看起来遍历整个数组,并且每次找到一个空格时,都会将条目添加到已构建字符串的末尾。然后,当没有空格时,它将检查是否有任何添加,并将其添加到输出值($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 :(得分:0)

我只修改了一点代码(实际上,我删除了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];

答案 3 :(得分:-2)

您可以像下面一样使用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);