2014-01-07 68 views
0

我有一個數組循環:顯示計數器

陣列功能:

$truckTypesArray = array( 

          "1" => "03 m3", 
          "2" => "05 m3", 
          "3" => "08 m3", 
          "4" => "10 m3", 
          "5" => "12 m3", 
          "6" => "14 m3", 
          "7" => "20 m3", 
          "8" => "20 m3 Hayon", 

          ); 


function getTruckTypes($truckTypesArray, $id) 
{ 
    return $truckTypesArray[$id]; 
} 

循環代碼:

while($fetchPresentTruckTypes = mysql_fetch_array($getTruckTypeQuery)) 
{ 
    $createTruckTypeArray[] = getTruckTypes($truckTypesArray, $fetchPresentTruckTypes['truckTypeId']);      

} 

$allTructTypes = implode(",",$createTruckTypeArray); 

現在它產生這個輸出很好:

20 m3, 03 m3, 20 m3, 10 m3, 20 m3, 

我希望它看起來是這樣的:

20 m3 = 3, 
03 m3 = 1, 
10 m3 = 1 
+0

試一下array_count_values() –

回答

1

使用this。它會爲您計算您的陣列並返回您所需的數據。

+0

你能在我的代碼上實現嗎? –

+0

嗯,不,但在PHP.net上的例子非常簡單,並會給你使用。像'$ models = array_count_values($ all_the_trucks);'或類似的東西。 – kinghfb

1
function createTruck($createTruckTypeArray){ 
    $result = array(); 
    foreach($createTruckTypeArray as $val){ 
    $result[$val] = array_count_values($val); 
    } 
    return $result; 
} 

這個函數返回一個數組這樣

array(
    '20 m3' => 3, 
    '03 m3' => 1, 
    '10 m3' => 1 
); 

這可以爆你的結果。不試試,請檢查

implode(', ', array_map(function ($v, $k) { return $k . '=' . $v; }, $result, array_keys($result)));