Odd Echo在foreach循环后添加一个字符串

时间:2014-05-13 11:38:08

标签: php xml

嘿伙计们在过去的半个小时里一直在撕扯我的头发,但是不能理解输出即将到来,不知何故,循环外的变量得到一个值,但在其工作正常的情况下,任何人都可以放弃吗?

private function retrieve_jobs ($xml){
        $i = 0;
        $job_id= "";
                foreach ($xml->result->rowset->row as $row) {
               if($i==10) { break;}
               $job = "".$row['jobID'].",";
               echo $job;

               $job_id = $job_id + $job;
        }
        echo "<hr>";
        echo $job_id;

    }

返回

    222306493,221469738,221347167,192148888,192148812,192148779,191545019,191544687,191431978,191410960,191404449,191394324,137944351,137241312,135658237,135611078,135586553,86984622,86984602,74752623,74655215,74546907,73206908,73206874,73204769,72540887,72539881,72489215,70936404,70931768,70911740,70907088,70907076,70891956,70702643,70702624,70588927,70424205,70423994,70423605,70399767,70394685,70372461,70372325,70354216,70336955,70236410,70236385,70062221,70055569,70055424,70039478,69734908,69733842,69716985,69716342,69706388,62723392,56140265,55035686,55034424,55020755,54975618,54972666,54961222,

(外循环号码) 6396595747不确定此数字的来源应该是上面的值。

3 个答案:

答案 0 :(得分:0)

在php中使用点.作为连接运算符,

$job_id = $job_id . $job;
                  ^

旁注:您在循环外获得的数字6396595747是您在循环中获得的所有数字的总和。

答案 1 :(得分:0)

PHP中,.用于连接,而不是+

E.G:

$job_id = $job_id . $job;

这也适用于字符串:

$str = "Hello";

$str .= ", how are you?";

echo $str; //Hello, how are you?

答案 2 :(得分:0)

正如PHP中提到的其他用户一样,您应该使用dot进行字符串连接。

同样在这种情况下,你可以使用implode函数,这个函数更清晰,而不是每次连接逗号。

示例:

private function retrieve_jobs ($xml){
    $i = 0;
    $job_ids = array();

    foreach ($xml->result->rowset->row as $row) {
       if($i==10) { break;}
       $job_ids[] = $row['jobID'];
       echo $row['jobID'];
    }

    echo "<hr>";
    echo implode(', ', $job_ids);
}