-1

我找不到一种方法来读取 URL、向量或文本形式中的变量,以便它只返回重复的值。如果只有一个值,我需要显示它,或者如果有所有不同的值,我需要显示它们。

例如,如果我有 1,2,3,1,4,我希望它显示 1,如果我有 1,2,3,4 显示所有这些。

$values = $_GET['intrebare'];
$count = count($values);

foreach($values as $val =>$array) 
{
    //echo $val . '<br/>';
    //var_dump($array);

    if(is_array($array))
    {
        var_dump($array);
    }
    else
    {
        echo $val;
    }
}
4

2 回答 2

1

您可以在输入数组上使用 array_unique 来查看是否没有双打。如果array_unique之后的数组和以前一样大,则应该打印所有值。

据我了解,如果数组不包含所有唯一值,则您希望打印多次出现的所有值。如果您只想打印多次出现的值,您可以首先使用array_count_values检查多次出现的值并打印它们。

剩下的就看你了:)

于 2011-12-29T14:49:45.387 回答
1

使用array_count_values是最简单的方法,但如果您需要掌握如何完成您正在寻找的内容,这里是详细版本。

$input = array(1, 2, 3, 4, 1);
$unique = array_unique($input);

// If $input and $unique are different in length, 
// there is one or more repeating values
if (count($input) !== count($unique)) {
    $repeat = array();

    // Sort values in order to have equal values next to each other
    sort($input);

    for ($i = 1; $i < count($input) - 1; $i++) {
        // If two adjacent numbers are equal, that's a repeating number.
        // Add that to the pile of repeated input, disregarding (at this stage)
        // whether it is there already for simplicity.
        if ($input[$i] === $input[$i - 1]) {
            $repeat[] = $input[$i];
        }
    }

    // Finally filter out any duplicates from the repeated values
    $repeat = array_unique($repeat);

    echo implode(', ', $repeat);
} else {
    // All unique, display all
    echo implode(', ', $input);
}

简洁的单线版本将是:

$input = array(1, 2, 3, 4, 1);
$repeat = array_keys(
    array_filter(
        array_count_values($input), 
        function ($freq) { return $freq > 1; }
    )
);

echo count($repeat) > 0 
        ? implode(', ', $repeat)
        : implode(', ', $input);
于 2012-01-04T13:37:14.877 回答