计算一行中具有相同值的数组中的键

时间:2013-12-26 18:59:56

标签: php arrays

例如我有这个数组:

array(
[0] => 'a',
[1] => 'b',
[2] => 'c',
[3] => 'b',
[4] => 'b',
[5] => 'b'
);

是否有一种优雅的方式可以理解最新的3个密钥连续'b'? 感谢您的任何建议

4 个答案:

答案 0 :(得分:0)

<?php
$array = ["3","3","a","b","a"];
$count_array = array();
foreach($array as $key => $value) {
    if(!in_array($value,$count_array)) {
        $count_array[$value][] = $key;
    }
}
echo "<pre>";
echo nl2br(print_r($count_array,true));
echo "</pre>";

foreach($count_array as $key => $value) {
echo $key . ":" . count($value)  . "<br>";
}
?>

输出:

Array
(
[3] => Array
    (
        [0] => 0

        [1] => 1
    )
[a] => Array
    (
        [0] => 2
        [1] => 4
    )
[b] => Array
    (
        [0] => 3
    )
 )
3:2
a:2
b:1

答案 1 :(得分:0)

如果你认为官方php功能优雅,我认为你不会找到它。但是你总能这样做自己:

function elegantCountWhatEver($array) {
    $counts =  array();
    $count = 0;
    $last = "";
    foreach($array as $key => $value) {
        if($value != $last) {
            array_push($counts, array($count, $last));
            $count = 0;
            $last = $value;
        }
      $count++;
    }
    array_shift($counts);
    array_push($counts, array($count, $value));
    return $counts;
}

这将返回如下数组:

Array
(
[0] => Array
    (
        [0] => 1
        [1] => a
    )

[1] => Array
    (
        [0] => 1
        [1] => b
    )

[2] => Array
    (
        [0] => 1
        [1] => c
    )

[3] => Array
    (
        [0] => 3
        [1] => b
    )
)

答案 2 :(得分:0)

你可以试试这个,然后循环$redundant阵列并随意显示:

<?php
$list = array('a','b','c','b','b','b','f','f','f','2','2','2','2','f','f');

$last_val = false;

$redundant = array();

$i = 0;

foreach($list as $k=>$v)
{
    if($last_val === $v)
    {
        if(isset($redundant[$i][$v]))
        {
            $redundant[$i][$v] += 1;
        }
        else
        {
            $redundant[$i][$v] = 2;
        }
    }
    else
    {
        $last_val = $v;
        $i++;
    }
}

echo '<pre>'.print_r($redundant, true).'</pre>';
?>

答案 3 :(得分:0)

我一直在寻找一种优雅的方式。 如果它是关于用循环执行它我已经用几行代码完成它。但我仍然不喜欢这个:D

$consec_red = 0;
$consec_black = 0;
$last_found = null;
$spins = array_reverse($spins);

foreach ($spins as $spin => $type) {
    if($consec_red  == 0 && $consec_black == 0)
        $last_found = $type;
    if ($type == 'red' && $last_found == 'red')
        $consec_red++;
    elseif ($type == 'black' && $last_found == 'black')
        $consec_black++;
    else
        break;
}