【发布时间】:2015-04-24 04:46:17
【问题描述】:
我想访问此数组中的数据以对其进行比较
$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
)
到第一个数组中的“房间”数组
这是我曾经这样做的循环,它有效,但我认为它有点丑陋和冗长。
// 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;
}
}
我知道它们不是大量的值数组,循环遍历不需要很长时间,但我想知道是否有更简洁的方法来做到这一点?
感谢您的帮助!
【问题讨论】:
-
递归就是答案
-
这可能是在Code Review SE 上提出的更好的问题。
-
也许 array_diff 有帮助...你看过了吗?
-
在研究了使用递归函数遍历数组之后,看起来这就是要走的路!
标签: php multidimensional-array foreach nested-loops