从数组中获取独特的顶级值

时间:2014-07-16 05:14:00

标签: php arrays

这是我的Object数组:

$prob[] = (object) array(
                        "value" => ($pos_Count + 1)/ ($totalPOS_count + $distinct_pos_Count),
                        "tag"   => $row1['tag'],
                        );

这里我正在排序并回显前5个(按值)数组值

    uasort ($prob, function($a, $b) {
    if ($a->value == $b->value) {
            return 0;
        }
        return ($a->value < $b->value) ? 1 : -1;
    });

    $prob = array_slice($prob, 0, 5);
    foreach ($prob as $array)
    {
        echo "Tag :". $array->tag." Probablity :".$array->value."<br/>";
    }

如果数组具有如下重复值:

Tag :Feedback Probablity :0.0085561497326203
Tag :Design Probablity :0.007177033492823
Tag :Design Probablity :0.007177033492823
Tag :services Probablity :0.006295907660021
Tag :services Probablity :0.006295907660021

它应该用它们的值打印不同的tags。而是为DesignServices打印相同标签两次。

这是正确的:

Tag :articles Probablity :0.0022321428571429
Tag :Fun Probablity :0.0012771392081737
Tag :Facebook Probablity :0.0012771392081737
Tag :delivery Probablity :0.0012771392081737
Tag :Supplier Probablity :0.0012771392081737

那么我怎么能在这里只回显不同的前5个标签/

1 个答案:

答案 0 :(得分:0)

这将替换array_slice以仅获取唯一标记:

$prob[] = (object) array("value" => "DISPLAY ME", "tag" => 1,);
$prob[] = (object) array("value" => "DO NOT DISPLAY ME","tag" => 1,);
$prob[] = (object) array("value" => "DISPLAY ME","tag"   => 2,);
$new_prob = array();
$count = 0;
foreach ($prob as $array) {
    if (!array_key_exists($array->tag, $new_prob)) {
        $new_prob[$array->tag] = $array->value;
        if (++$count == 5) { // Number of unique elements to keep
            break;
        }
    }
}

foreach ($new_prob as $key => $value) {
    echo "Tag :". $key." Probablity :".$value."<br/>";
}

结果:

Tag :1 Probablity :DISPLAY ME
Tag :2 Probablity :DISPLAY ME