2012-10-21 167 views
-2

說我有一個一個數組是這樣的:從「標籤」的陣列創建陣列

Array (
    [0] => "bananas, apples, pineaples" 
    [1] => "bananas, show cones" 
    [2] => "" 
    [3] => "apples, santa clause" 
.. 
) 

這個數組我想創建一個新的數組,抱在一起的「標籤」,並且次數它occuredd第一陣列中,preferebly按字母順序排序,這樣的:

Array (
    [apples] => 2 
    [bananas] => 2 
.. 
) 

array (
    [0] => [apples] => 2 
.. 
) 
+0

那麼你有什麼試過嗎?這很簡單。 – Sirko

回答

0
// array to hold the results 
$start = array("bananas, apples, pineaples", "bananas, show cones", "", "apples, santa clause"); 
// array to hold the results 
$result = array(); 

// loop through each of the array of strings with comma separated values 
foreach ($start as $words){ 

    // create a new array of individual words by spitting on the commas 
    $wordarray = explode(",", $words); 
    foreach($wordarray as $word){ 
     // remove surrounding spaces 
     $word = trim($word); 
     // ignore blank entries 
     if (empty($word)) continue; 

     // check if this word is already in the results array 
     if (isset($result[$word])){ 
      // if there is already an entry, increment the word count 
      $result[$word] += 1; 
     } else { 
      // set the initial count to 1 
      $result[$word] = 1; 
     } 
    } 
} 
// print results 
print_r($result); 
0

假設你的第一個數組爲$array,和你的結果數組作爲$tagsArray

foreach($array as $tagString) 
{ 
    $tags = explode(',', $tagString); 
    foreach($tags as $tag) 
    { 
     if(array_key_exists($tag, $tagsArray)) 
     { 
      $tagsArray[$tag] += 1; 
     } 
     else 
     { 
      $tagsArray[$tag] = 1; 
     } 
    } 

}

0

您可以嘗試使用array_count_values

$array = Array(
     0 => "bananas, apples, pineaples", 
     1 => "bananas, show cones", 
     2 => "", 
     3 => "apples, santa clause"); 

$list = array(); 
foreach ($array as $var) { 
    foreach (explode(",", $var) as $v) { 
     $list[] = trim($v); 
    } 
} 
$output = array_count_values(array_filter($list)); 
var_dump($output); 

輸出

array 
    'bananas' => int 2 
    'apples' => int 2 
    'pineaples' => int 1 
    'show cones' => int 1 
    'santa clause' => int 1