2012-10-21 39 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