查找多维数组中的连续出现php [已关闭]

rjee0c15  于 2023-09-29  发布在  PHP
关注(0)|答案(2)|浏览(95)

已关闭,此问题需要details or clarity。它目前不接受回答。
**想改善这个问题吗?**通过editing this post添加详细信息并澄清问题。

昨天关门了。
这篇文章是编辑并提交审查22小时前.
Improve this question

Array
(
    [0] => Array
        (
            [0] => OLAO01
            [1] => OLAO01
            [2] => BARR04
            [3] => OLAO01
            [4] => MADD03
        )

    [1] => Array
        (
            [0] => BARR04
            [1] => POWE03
        )

    [2] => Array
        (
            [0] => BARR04
            [1] => COLL09
        )

    [3] => Array
        (
            [0] => BARR04
            [1] => SARC01
            [2] => OLAO01
        )

    [4] => Array
        (
            [0] => BARR04
            [1] => HORS02
        )

    [5] => Array
        (
            [0] => BARR04
        )

    [6] => Array
        (
            [0] => OLAO01
        )

    [7] => Array
        (
            [0] => RYDE02
        )

    [9] => Array
        (
            [0] => CAMP02
        )

    [10] => Array
        (
            [0] => WRIG05
            [1] => CAMP02
            [2] => LEMO01
        )

    [11] => Array
        (
            [0] => OLAO01
        )

    [12] => Array
        (
            [0] => HIPP01
            [1] => LEMO01
        )
)

我有这样的数组,我需要找到如果有多少次一个值重复连续BARR04
重复6次。但是如果一个数组不是那个值,那么对于那个计数器,它将再次设置为1

$result = array_intersect($newary[$i], $newary[$i+1]);

我试着用这个,但不能正常工作

gmol1639

gmol16391#

遍历子数组并跟踪"BARR04"的连续出现:

$arr = [
    ["OLAO01", "OLAO01", "BARR04", "OLAO01", "MADD03"],
    ["BARR04", "POWE03"],
    ["BARR04", "COLL09"],
    ["BARR04", "SARC01", "OLAO01"],
    ["BARR04", "HORS02"],
    ["BARR04"],
    ["OLAO01"],
    ["RYDE02"],
    ["CAMP02"],
    ["WRIG05", "CAMP02", "LEMO01"],
    ["OLAO01"],
    ["HIPP01", "LEMO01"]
];

$target = "BARR04";
$consecutiveCount = 0;
$maxConsecutiveCount = 0;

foreach ($arr as $subarr) {
    if (in_array($target, $subarr)) {
        // if the value is present in the subarray, update the count
        $consecutiveCount++;
        if ($consecutiveCount > $maxConsecutiveCount) {
            $maxConsecutiveCount = $consecutiveCount;
        }
    } else {
        // if the value is not present the streak is broken and you reset the count
        $consecutiveCount = 0;
    }
}

echo "The value '$target' repeats consecutively $maxConsecutiveCount times.";
piv4azn7

piv4azn72#

您可以展平数组并计算某个值出现的次数。就像这样:

$array = [
    ["OLAO01", "OLAO01", "BARR04", "OLAO01", "MADD03"],
    ["BARR04", "POWE03"],
    ["BARR04", "COLL09"],
    ["BARR04", "SARC01", "OLAO01"],
    ["BARR04", "HORS02"],
    ["BARR04"],
    ["OLAO01"],
    ["RYDE02"],
    ["CAMP02"],
    ["WRIG05", "CAMP02", "LEMO01"],
    ["OLAO01"],
    ["HIPP01", "LEMO01"]
];

function getValueCount($array, $value){
    $flattened = array_merge(...$array);
    $count = array_count_values($flattened);
    return $count[$value] ?? 0;
}

像这样使用:

echo getValueCount($array, "BARR04");

相关问题