2013-10-14 28 views
0

假設的最後一個項目中刪除逗號我有此數組:PHP:從數組

['Jun 13',529], 

['Jul 13',550], 

['Aug 13',1005], 

['Sep 13',1021], 

['Oct 13',1027], 

什麼是從上面的數組中刪除逗號的最後一個項目最快/最簡單的方法是什麼?

因此結果數組只包含這些值:

['Jun 13',529], 

['Jul 13',550], 

['Aug 13',1005], 

['Sep 13',1021], 

['Oct 13',1027] 

實際代碼:提前

$i = 0; 
while($graph_data = $con->db_fetch_array($graph_data_rs)) 
{ 
    $year = $graph_data['year']; 
    $month = $graph_data['month']; 
    $count = $graph_data['count']; 
    $total_count = $graph_data['total_count']; 

    // for get last 2 digits of year 
    $shortYear = substr($year, -2, 2); 

    // for get month name in Jan,Feb format 
    $timestamp = mktime(0, 0, 0, $month, 1); 
    $monthName = date('M', $timestamp); 

    $data1 = "['".$monthName.' '.$shortYear."',".$total_count."],"; 

    $i++; 
} 

謝謝...

+9

你是怎麼產生這個 '數組'? –

+0

這個數組的關鍵是什麼?這些值是字符串嗎? – Nanne

+0

檢查'implode'函數 –

回答

1
  • 如果你有那陣陣Ÿ在變量中,希望有一個字符串,可以使用implode獲得由字符分隔的字符串。
  • 如果你已經有了一個字符串,可以使用rtrim刪除最後一個字符的字符串的右側。
  • 如果你有一個數組,其中的值是一個字符串['Oct 13',1027](以逗號結尾),你有上面相同的選項和:
    • 您可以使用array_walk有一些提到的功能
    • 你可以得到的最後一個元素,並在其上使用rtrim像下面的代碼:

      :一個字符串數組使用rtrim的代碼

實施例

<?php 
$values = array("['Oct 13',1027],", "['Oct 13',1027],"); 
$lastIndex = count($values)-1; 
$lastValue = $values[$lastIndex]; 
$values[$lastIndex] = rtrim($lastValue, ','); 
1
<?php 
$arr = array(
    "['Jun 13',529],", 
    "['Jul 13',550]," 
); 
$arr[] = rtrim(array_pop($arr), ', \t\n\r'); 
print_r($arr); 

// output: 

// Array 
// (
//  [0] => ['Jun 13',529], 
//  [1] => ['Jul 13',550] 
//) 
0

使它成爲一個實際的陣列,和崩潰。不確定將會發生什麼(如果json:你可以做得更好,而不是將它們自己僞裝成數組,但是這對讀者來說是一個exersize)。

$yourData = array(); 
while(yourloop){ 
    //probaby something like: $yourData = array($monthName=>$total_count); 
    $yourData[] = "['".$monthName.'&nbsp;'.$shortYear."',".$total_count."]"; 
} 
//now you have an actual array with that data, instead of a fake-array that's a string. 
//recreate your array like so: 
$data1 = implode(','$yourData); 
//or use json_encode. 
+0

請看實際的代碼 –

+0

爲什麼?這應該讓你去 - >把你的東西放在一個數組中,然後你應該看看json_encode – Nanne

0

與@srain類似的東西,但使用array_push

$values = array("['Oct 13',1027],", "['Oct 13',1027],"); 

$last = array_pop($values); //pop last element 
array_push($values, rtrim($last, ',')); //push it by removing comma 

var_dump($values); 

//output 
/* 

array 
    0 => string '['Oct 13',1027],' (length=16) 
    1 => string '['Oct 13',1027]' (length=15) 

*/