我已经尝试了一段时间,并且无法绕过它。我有两个数组。一个数组包含名为$sendatas
的传感器信息,另一个数组包含将这些传感器分配到调用$zones
的位置。
我希望能够在表格行中创建动态HTML复选框,具体取决于传感器是否已分配给区域,如果是,则显示已选中的复选框,如果不是,则显示未选中复选框。
这是我的数组的一个例子:
$sendatas
数组:
[1] => Array
(
[hwserial] => 00002025
[name] => FG05 Room Temp
[serial] => 5
[chan] => 1
[alarmhigh] => 30
[alarmlow] => 5
[delay] => 10
)
[2] => Array
(
[hwserial] => 00002025 01
[name] => FG05 Kitchen 1 Freezer
[serial] => 5
[chan] => 2
[alarmhigh] => -10
[alarmlow] => -35
[delay] => 10
)
$zones
数组:
[0] => Array
(
[serial] => 1
[idGrid] => 50
[name] => All Sensors
)
[1] => Array
(
[serial] => 1
[idGrid] => 52
[name] => Food Area
)
[2] => Array
(
[serial] => 2
[idGrid] => 50
[name] => All Sensors
)
[3] => Array
(
[serial] => 2
[idGrid] => 52
[name] => Food Area
)
[4] => Array
(
[serial] => 3
[idGrid] => 50
[name] => All Sensors
)
[5] => Array
(
[serial] => 3
[idGrid] => 52
[name] => Food Area
)
[6] => Array
(
[serial] => 4
[idGrid] => 50
[name] => All Sensors
)
我的两个区域的长度不一样。我希望能够实现的是通过查找与两个数组匹配的串行键来创建一个看起来像这样的数组。
Array
(
[0] => Array
(
[hwserial] => 00001216
[name] => Fridge Office Thermal
[serial] => 1
[chan] => 1
[alarmhigh] => 8
[alarmlow] => -2
[delay] => 10
[idGrid1] => 50
[idGrid2] => 51
[idGrid3] => 52
[zonename1] => All Sensors
[zonename2] => Office
[zonename3] => Food Area
)
[1] => Array
(
[hwserial] => 00002025
[name] => FG05 Room Temp
[serial] => 5
[chan] => 1
[alarmhigh] => 30
[alarmlow] => 5
[delay] => 10
[idGrid] => 50
[idGrid] => Not Used
[idGrid] => 52
[zonename1] => All Sensors
[zonename2] => Not Used
[zonename3] => Food Area
)
我很确定一旦我正确格式化了这个数组,我就可以为复选框编写代码。我已经尝试过使用一些foreach循环,但只是继续弄乱它。到目前为止,我已经试了好几个星期,希望它能来找我,但它没有。任何帮助表示赞赏。
答案 0 :(得分:0)
这应该只是创建一个新数组(让它称为$ combined),它是$ sendatas数组之一的克隆,但使用[serial]作为键,以便你可以定位具体项目。你可以遍历$ zones数组,并检查每个项是否在$ combo中找到[serial],如果找到匹配,则将[idgrid]和[name]注入$ combined ['串行&#39]。由于您没有使用子数组,您可以添加一个计数器来添加递增数量的值。
答案 1 :(得分:-1)
根据这一点,应该可以解决这个问题:
$results = [];
foreach ($sendatas as $sensor) {
$zone_counter = 0;
foreach ($zones as $zone) {
if ($zone['serial'] == $sensor['serial']) {
$zone_counter++;
$sensor['idGrid' . $zone_counter] = $zone['idGrid'];
$sensor['zonename' . $zone_counter] = $zone['name'];
}
}
$results[] = $sensor;
// if you only want $results to contain sensors that actually have zones,
// wrap it in an if-statement:
// if ($zone_counter > 0) {
// $results[] = $sensor;
// }
}
print_r($results);
请注意,这不会为您提供带有您提供的数据的匹配区域的传感器,因为这两个传感器都有[serial] => 5
,并且您的所有区域都有[serial] => 1
到4
。如果您想通过其他键而不是串行匹配,只需更改if语句。