-2

假设我有一个这样的数组:

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

从该数组中,我想创建一个新数组,保存每个“标签”,以及它在第一个数组中出现的次数,最好按字母顺序排序,如下所示:

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

或者

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

3 回答 3

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);
于 2012-10-21T13:52:58.537 回答
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;
        }
    }

}

于 2012-10-21T13:55:17.743 回答
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
于 2012-10-21T13:58:46.940 回答