如何在数组中获得热门关键字

时间:2015-09-03 11:13:41

标签: php arrays sorting

我有一个包含我网站所有关键字的数组:

Array
(
    [0] => keyword1
    [1] => keyword1
    [2] => keyword1
    [3] => keyword1
    [4] => keyword1
    [5] => keyword1
    [6] => keyword1
    [7] => keyword1
    [8] => keyword1
    [9] => keyword1
    [10] => keyword2
    [11] => keyword2
    [12] => keyword2
    [13] => keyword3
    [14] => keyword3
    [15] => keyword3
    [16] => keyword3
    [17] => keyword3
    [18] => keyword3
    [19] => keyword4
    [20] => keyword4
    [21] => keyword4
    [22] => keyword4
    [23] => keyword4
    [24] => keyword5
)

我想找到热门关键词,创建一个像这样的数组:

Array
(
    [0] => Array
        (
            [0] => keyword1
            [count] => 10
        )

    [1] => Array
        (
            [0] => keyword2
            [count] => 3
        )

    [2] => Array
        (
            [0] => keyword3
            [count] => 6
        )

    [3] => Array
        (
            [0] => keyword4
            [count] => 5
        )

    [4] => Array
        (
            [0] => keyword5
            [count] => 1
        )

)

此外,我想按关键字排序并删除重复值并在子数组中设置每个关键字。

4 个答案:

答案 0 :(得分:0)

只需使用array_count_values()

答案 1 :(得分:0)

$test=your array; //store your array in a variable
$val = array_count_values($test); //count your array values
print_r($val);

答案 2 :(得分:0)

array_count_values会将计数输出为

Array
(
    [keyword1] => 10
    [keyword2] => 3
    [keyword3] => 6
    [keyword4] => 5
    [keyword5] => 1
)

但是对于您想要的输出,您需要使用foreach

enter image description here

$arra = Array
(
    0 => "keyword1",
    1 => "keyword1",
    2 => "keyword1",
    3 => "keyword1",
    4 => "keyword1",
    5 => "keyword1",
    6 => "keyword1",
    7 => "keyword1",
    8 => "keyword1",
    9 => "keyword1",
    10 => "keyword2",
    11 => "keyword2",
    12 => "keyword2",
    13 => "keyword3",
    14 => "keyword3",
    15 => "keyword3",
    16 => "keyword3",
    17 => "keyword3",
    18 => "keyword3",
    19 => "keyword4",
    20 => "keyword4",
    21 => "keyword4",
    22 => "keyword4",
    23 => "keyword4",
    24 => "keyword5"
);

$newarray = array_count_values($arra);
$output = array();
foreach($newarray as $key=>$val) {
    $output[] = array("0"=>$key, "count"=>$val);
}

echo '<pre>';print_r($output);echo '</pre>';

<强>输出:

Array
(
    [0] => Array
        (
            [0] => keyword1
            [count] => 10
        )

    [1] => Array
        (
            [0] => keyword2
            [count] => 3
        )

    [2] => Array
        (
            [0] => keyword3
            [count] => 6
        )

    [3] => Array
        (
            [0] => keyword4
            [count] => 5
        )

    [4] => Array
        (
            [0] => keyword5
            [count] => 1
        )

)

答案 3 :(得分:0)

您可以使用此功能

  <?php
$items = Array(
             'keyword5','keyword5','keyword5','keyword5','keyword1','keyword1','keyword1','keyword2'
        );

$occurences = array_count_values($items);
print_r($occurences);

?>

它会打印出类似值的计数。