加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

检查PHP中多个数组索引的值

发布时间:2020-12-13 17:43:26 所属栏目:PHP教程 来源:网络整理
导读:我想检查一组图像文件名,看看有多少连续图像使用 PHP具有相同的方向. 在下面的示例中,我想知道索引1到4具有相同的方向,或者在第一个索引处有四个具有相同方向的连续图像. 作为参考,“方向”值对于垂直方向是“V”而对于水平方向是“H”. 例如., Array([0] =
我想检查一组图像文件名,看看有多少连续图像使用 PHP具有相同的方向.

在下面的示例中,我想知道索引1到4具有相同的方向,或者在第一个索引处有四个具有相同方向的连续图像.

作为参考,“方向”值对于垂直方向是“V”而对于水平方向是“H”.

例如.,

Array
(
[0] => Array
    (
        [filename] => image0.jpg
        [orientation] => V
    )

[1] => Array
    (
        [filename] => image1.jpg
        [orientation] => H
    )

[2] => Array
    (
        [filename] => image2.jpg
        [orientation] => H
    )

[3] => Array
    (
        [filename] => image3.jpg
        [orientation] => H
    )

[4] => Array
    (
        [filename] => image4.jpg
        [orientation] => H
    )
[5] => Array
    (
        [filename] => image5.jpg
        [orientation] => V
    )
[...]
[n]
}

必须有一个更好的方式

if ([i]['orientation'] == [i+1]['orientation'])
if ([i]['orientation'] == [i+1]['orientation'] == [i+2]['orientation'])
if ([i]['orientation'] == [i+1]['orientation'] == [i+2]['orientation']  == [i+3]['orientation'])
if ([i]['orientation'] == [i+1]['orientation'] == [i+2]['orientation'] == [i+3]['orientation'] == [i+4]['orientation'])

解决方法

如果我理解您尝试应用的逻辑,SplQueue提供了所有功能,可以彻底和整齐地解决您的问题.

我写了这个,根据你提供的用例,我测试得很好.

// your data array
$array = array(
    array("filename"=>"image0.jpg","orientation"=>"V"),array("filename"=>"image1.jpg","orientation"=>"H"),array("filename"=>"image2.jpg",array("filename"=>"image3.jpg",array("filename"=>"image4.jpg","orientation"=>"H"));


function queue($array) {

    // grab a new SqlQueue object -- http://php.net/manual/en/class.splqueue.php    
    $q = new SplQueue;
    foreach($array as $key=>$val) {
        // if this is the first iteration or the queue object was emptied out
        if ($q->isEmpty()) {
            $q->enqueue($val);
        } else {

            if ($val['orientation'] == $array[$key--]['orientation']) {
                $q->enqueue($val);
                if (($q->count() % 4) == 0) {
                    return $q;
                }
            } else {
                // Dequeue the whole group on interrupt
                while ($q->valid()) {
                   $q->dequeue();
                }
                // ... and start filling the queue,the mismatch as the new pattern
                $q->enqueue($val);
            }
        }
    }
}

$q = queue($array);
echo $q->count();

data属性enqueued()设置是私有的,因此您必须在类中使其可见.

如果您使用的是PHP 5.4,则可以使用函数数组解除引用替换该递减的数组索引调用,如下所示:

if ($val['orientation'] == prev($array[$key])['orientation'] {
    //...

其他一切都非常标准.模数测试一旦获取连续的4个匹配就返回队列对象,因为SplQueue对象强制执行有序的索引FIFO,并且不能被排除.最后,如果在队列连续4个匹配之前匹配中断,则Spl的迭代器会清空队列以重新开始 – 从不匹配开始(第一个新模式).

那应该涵盖一切……

HTH

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读