0

我有以下代码来遍历一个数组并从结果中构建一个字符串:

$finalstring;
$tempstring;

foreach($arr as $key => $value)
{
     $i = 0;
    foreach($value as $key1 => $value1)
    {
        $i+= 1;

        if($i == 1)
        {           

            $tempstring . $value1 . "|";

        }
        if($i == 2)
        {   

            $tempstring . $value1 . "|||||";

        }
        if($i == 3)
        {   

            $tempstring  . $value1 . "||||||||||";

        }
        if($i == 4)
        {    

            $tempstring  . $value1 . "|||||||||||||||||\n";

        }

    }

            echo $tempstring;
            $finalstring . $tempstring;

}
            echo $finalstring;

但是,代码似乎不是在构建字符串(数组绝对不是空的,它的格式如下 -

Array
(
    [0] => Array
        (
            [Name] => Ron
            [Date] => 9/23/10
            [Title] => Boss
            [Activity] => Soccer
        )

    [1] => Array
        (
            [Name] => Tim
            [Date] => 9/23/10
            [Title] => player
            [Activity] => Soccer
        )

    [2] => Array
        (
            [Name] => Jim
            [Date] => 9/23/10
            [Title] => manager
            [Activity] => Soccer
        )

    [3] => Array
        (
            [Name] => Lud
            [Date] => 9/23/10
            [Title] => employee
            [Activity] => Soccer
        )

    [4] => Array
        (
            [Name] => Ron
            [Date] => 9/23/10
            [Title] => sub boss
            [Activity] => Soccer
        )

    [5] => Array
        (
            [Name] => Lev
            [Date] => 9/23/10
            [Title] => mini boss
            [Activity] => Soccer
        )

    [6] => Array
        (
            [Name] => Timpthy
            [Date] => 9/23/10
            [Title] => super boss
            [Activity] => Soccer
        )

    [7] => Array
        (
            [Name] => Jimbo
            [Date] => 9/23/10
            [Title] => final battle
            [Activity] => Soccer
        )

    [8] => Array
        (
            [Name] => El
            [Date] => 9/23/10
            [Title] => link
            [Activity] => Soccer
        )

)

是否有任何原因导致代码无法同时构建$tempstring$finalstring(我的意思是 echo 语句没有输出值)?

4

3 回答 3

5

你应该像这样构建它:

$tempstring .= $value1 . "|";
于 2013-10-21T13:48:34.183 回答
2

我不知道你为什么要这样做,但错误是你没有分配连接值。事实上,连接结果不会去任何地方,即使它被计算(不确定它是否被评估,因为我怀疑解释器有内置的优化,只会完全忽略评估)

代替:

$tempstring . $value1 . "|";

你应该写:

$tempstring .= $value1 . "|";

或以速记:

$tempstring = $tempstring . $value1 . "|";
于 2013-10-21T13:52:19.310 回答
1

$finalstring将and初始化$tempstring为空字符串。并且每次您想将值存储到变量时,例如使用这个

$tempstring .= $value1 . "|";

记得放=以便值可以合并

于 2013-10-21T13:51:58.060 回答