2017-06-01 25 views
0

我想Concat的作者名,當有一個文章,但由於某種原因,它增加了額外的逗號以上的作者。這是使用代碼IM:用於級聯添加額外的逗號

 $get_coauthors = get_coauthors(); 
    $count = count($get_coauthors); 
    if ($count > 1) { 
     for ($i = 0; $i <= $count; $i++) { 
      $name .= $get_coauthors[ $i ]->data->display_name . ' ,'; 
     } 
    } else { 
     $name = $get_coauthors[0]->data->display_name; 
    } 
    error_log(print_r($name,true)); 

而我的print_r將返回user1 ,user2 , ,

任何IDEIA爲什麼?

+0

請張貼的print_r的'結果($ get_coauthors)' –

+0

不能肯定地說,沒有看到你的數據,但我要去猜測的一個作者命名爲空。 – Carcigenicate

+0

你的循環比你的陣列和捉迷藏到一個一次出現較大的不存在'爲($ i = 0; $ I <= $計數; $ I ++){'它修改爲'爲($ I = 0; $我<$ count; $ i ++){'** Set'<?php error_reporting(E_ALL);函數ini_set(「display_errors設置」,1);'**,你會看到你的錯誤報道 – RiggsFolly

回答

2

無需爲count()if聲明。這可能是簡單的:

//If you already have a $name 
$names[] = $name; 

foreach(get_coauthors() as $author) { 
    $names[] = $author->data->display_name; 
} 
$names = implode(', ', $names); 

要刪除任何清空:

$names = implode(', ', array_filter($names)); 
+0

謝謝你,那正是我需要的。 – anon123346

0

可以使用rtrim()去年刪除,從你的名單。

$srting = 'a,b,c,d,e,'; 
$result_output = rtrim($srting); 
echo $result_output; 

然後輸出:a,b,c,d,e

所以你的代碼會

$names = ''; 
foreach(get_coauthors() as $author) { 
    $names .= $author->data->display_name. ' ,'; 
} 
$result = rtrim($names,","); 

或獲得陣列中的所有名字,那麼剛剛破滅,那麼你會得到結果像USER1,users2等

$names = array(); 
foreach(get_coauthors() as $author) { 
    $names = $author->data->display_name; 
} 
$names = implode(', ', $names); 

有關數組更多幫助破滅

http://php.net/manual/pt_BR/function.implode.php