gpt4 book ai didi

php在循环内搜索数组

转载 作者:行者123 更新时间:2023-12-04 06:03:54 25 4
gpt4 key购买 nike

假设我有以下数组 $diff .

a, a, a, a, b, b, b, a, a, b, b, b, a, a, a, b

A represents a value inside $diff.
B represents an Array inside $diff.

现在我要数 A如果发生了 more than two times在其序列和 is not an Array ( instead a value )。否则,忽略它。

对于上述输入,代码应如下所示
[a] = not an array; 0
[a,a] = not an array; 0
[a,a,a] = not an array; 3
[a,a,a,a] = not an array; 4
[b] = array;
[b,b] = array;
[b,b,b] = array;
[a] = not an array; 0
[a,a] = not an array; 0
[b] = array;
[b,b] = array;
[b,b,b] = array;
[a] = not an array; 0
[a,a] = not an array; 0
[a,a,a] = not an array; 3
[b] = array;

这是我的尝试,但它不起作用!,由于值被替换,值被更改。
<?php

foreach($diff as $key => $val) {

if (!is_array($diff[$key])) { // THIS MEANS THAT THE CURRENT ELEMENT IS NOT AN ARRAY.
if(is_array($diff[$key-1]) ) { //START OF SEQ. IF THE PREVIOUS ELEMENT IS AN ARRAY AND CURRENT ELEMENT IS NOT AN ARRAY.

$SEQ_START=$key;
$n=1;

for($i=0; $i<=count($diff); $i+=1) { // I AM CHECKING HERE IF THE NEXT 3 ELEMENTS are NOT ARRAY, HENCE I CAN INCREMENT IT

if(!is_array($diff[$SEQ_START+$i])) $n+=1;
else $n=0;
}
}
}
}

?>

最佳答案

更新 根据下面@Grexis 的评论

$diff = array(array(),'a', 'a', 'a', 'a', array(), array(), array(), 'a', 'a', array(), array(), array(), 'a', 'a', 'a', array());

// Counter to hold current sequence total
$count = 0;
// Array to hold results
$counted = array();

// Loop array
foreach ($diff as $key => $val) {
if (is_array($val)) { // If it is an array
if ($count > 2) { // If the counter is more than 2
$counted[(isset($seq)) ? $seq + 1 : 0] = $count; // add it to the array
}
// Reset the counter
$count = 0;
$seq = $key;
} else {
// Increment the counter
$count++;
}
}
// If there is a >2 counter at the end, add one more result
if ($count > 2) {
$counted[(isset($seq)) ? $seq + 1 : 0] = $count;
}

print_r($counted);
// Outputs:
// Array
// (
// [0] => 4
// [12] => 3
// )

// or if you want the total count
$total = array_sum($counted);
echo $total; // 7

See it working

关于php在循环内搜索数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8602191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com