说我有一个像这样的数组:
Array (
[0] => "bananas, apples, pineaples"
[1] => "bananas, show cones"
[2] => ""
[3] => "apples, santa clause"
..
)
从那个数组我想创建一个新数组,保存每个“标记”,以及它在第一个数组中出现的次数,最好按字母顺序排序,如下所示:
Array (
[apples] => 2
[bananas] => 2
..
)
或
array (
[0] => [apples] => 2
..
)
答案 0 :(得分: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);
答案 1 :(得分: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;
}
}
}
答案 2 :(得分: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