序列中的PHP数组值

时间:2013-12-25 06:47:55

标签: php arrays string

您好我正在从我的数据库中检索值到我的网页。 这是我的代码

foreach ($rows as $r) { 
    echo $r->title;
}

现在我想将所有标题值保存在一个以逗号分隔的变量中,例如

$new_var = title_1,title_2,title_3;

我该怎么办?

7 个答案:

答案 0 :(得分:2)

$items = array();
foreach ($rows as $r)
        { 

$items[] = $r->title;

}

$new_var = implode(",", $items);

使用内爆。这是快速而简单的,并且处理必须用其他方法修复的尾随逗号的问题。

答案 1 :(得分:1)

使用implode:

$new_var = array();
foreach ($rows as $r) { 
    echo $r->title;
    $new_var[] = $r->title;
}
$new_var = implode(',',$new_var);

答案 2 :(得分:1)

使用追加

 $s='', 
   foreach ($rows as $r)
            { 
     $s.=$r->title.',';// for title1,title2
    // $s.="'".$r->title."'".","; // if you want 'title1','title2'
    //or    use like $s.="'$r->title',"; 
     } 
     $s=  substr($s, 0,-1);//remove last comma
   echo $s;

答案 3 :(得分:1)

$titles =  array();    
foreach ($rows as $r)
{ 
    $titles[] = $r->title;
}    
$new_var = implode(',' , $titles);

http://php.net/function.implode

答案 4 :(得分:1)

如果从MySQL中获取值,这可能会有所帮助并且是一种优化方式,

这不仅仅是针对替代选项的问题的答案

注意 GROUP_CONCAT有限制请在查询超过1028个字符之前检查它。

请参考此示例

http://www.mysqlperformanceblog.com/2006/09/04/group_concat-useful-group-by-extension/

CREATE TABLE services (
id INT UNSIGNED NOT NULL,
client_id INT UNSIGNED NOT NULL,
KEY (id));

INSERT INTO services
VALUES (1,1),(1,2),(3,5),(3,6),(3,7);

SELECT id,client_id FROM services WHERE id = 3;

+----+-----------+
| id | client_id |
+----+-----------+
|  3 |         5 |
|  3 |         6 |
|  3 |         7 |
+----+-----------+

SELECT id,GROUP_CONCAT(client_id) FROM services WHERE id = 3 GROUP BY id;

+----+-------------------------+
| id | GROUP_CONCAT(client_id) |
+----+-------------------------+
|  3 | 5,6,7                   |
+----+-------------------------+

答案 5 :(得分:0)

你可以使用array_map进行明显的循环。

$test_array = [(object) ['title' => 1], (object) ['title' => 2], (object) ['title' => 3]];

$result = implode(',', array_map(function($item)
            { return $item->title; }, $test_array));

var_dump($result); // string(5) "1,2,3"

Demo.

答案 6 :(得分:0)

可以使用String加入“,”和implode ..

$a=array();
foreach ($rows as $r) {   
    $a[]="'".$r->title."'";
}
echo implode(",", $a);