gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 22:13:14 25 4
gpt4 key购买 nike

我想使用 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","orientation"=>"H"),
array("filename"=>"image3.jpg","orientation"=>"H"),
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();

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

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

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

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

这应该涵盖所有内容......

HTH:)

关于php - 检查 PHP 中多个数组索引的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13872588/

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