PHP:比这些嵌套循环更好的方法?

时间:2015-02-22 22:19:40

标签: php multidimensional-array foreach nested-loops

我想访问此数组中的数据以对其进行比较

$roomSensors =

Array
(
    [maple] => Array
        (
            [room1] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                )

            [room2] => Array
                (
                    [0] => 4
                    [1] => 5
                    [2] => 6
                )

        )
)

我想比较一组这样的数字:

$sensorsInHit =

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

到第一个数组中的'room'数组

继承了我曾经做过的这个循环,它有效,但我觉得它有点丑陋而且长篇大论。

// each 'ward' has an array of 'rooms'

foreach ($roomSensors as $ward => $rooms) {

                // looping through each room in the rooms array
                // the values are arrays of bluetooth sensor ids

                foreach ($rooms as $room => $sensors){

                    // at this point i would like to just compare
                    // the sensorsInHit array to the $sensors array
                    // but i couldnt find a function that allows
                    // to see if one of the values in one array
                    // is equal to one of the values in another array
                    // so i just loop through the array and compare
                    // and compare single values to the array

                    foreach ($sensorsInHit as $sensor){                      

                        if (in_array($sensor, $sensors)){

                            // do loads of stuff

                            break;
                        }                        
                    }
                    break;
                }
}

取消注释

foreach ($roomSensors as $ward => $rooms) {

                foreach ($rooms as $room => $sensors){

                    foreach ($sensorsInHit as $sensor){                      

                        if (in_array($sensor, $sensors)){

                            // do loads of stuff                             

                            break;
                        }                        
                    }
                    break;
                }
}

我知道它们不是庞大的数值阵列,并且不需要花很长时间才能完成,但我想知道是否有更清洁的方法可以做到这一点?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以使用PHP array_intersect函数:

foreach ($roomSensors as $ward => $rooms) {
    foreach ($rooms as $room => $sensors){
        $matches = array_intersect($sensors, $sensorsInHit);
        if (count($matches) > 0){
            // do loads of stuff  
            break;
        }                           
    }
}

匹配将包含$ sensors中的所有值,这些值也在$ sensorsInHit中。

相关问题