我有两个foreach循环。在第一个foreach循环菜单列表和第二个foreach循环是数据库提取循环。所以我想比较第一个foreach键和第二个foreach值第一个foreach数组结果显示
Array
(
[master/city] => City
[master/national_holiday] => National Holiday
[master/operator_comments] => Operator Comments
[master/sensors] => Sensors
)
和第二个foreach数组结果
Array
(
[0] => Array
(
[menu_url] => monitoring/tickets
[menu_category] => monitoring
[read] => 1
[write] => 1
)
[1] => Array
(
[menu_url] => monitoring/serach_tickets
[menu_category] => monitoring
[read] => 1
[write] => 1
)
[2] => Array
(
[menu_url] => master/national_holiday
[menu_category] => monitoring
[read] => 1
[write] => 0
)
)
我尝试使用此代码但不能正常工作
foreach( $first_array as $key => $value) {
foreach( $second_array as $second ) {
if ($second['value'] == $key) {
echo "Hi";
}
}
}
你能说出我的错误吗?
我在视图中使用的真实代码
<?php
$i = 1;
foreach($first_array as $k => $val) {
?>
<tr>
<td>{{ $i }}</td>
<td class="mailbox-name">{{ $val }}</td>
<?php
foreach ($edit_rights['role_rights'] as $rights) {
?>
<td><input type="checkbox" class="master_read" name="menu_master_read[]" <?php if ($rights['menu_url'] == $k) { echo 'checked'; } else {echo ''; }?> value="{{ $k }}"></td>
<td><input type="checkbox" class="master_write" name="menu_master_write[]" value="{{ $k }}"></td>
</tr>
<?php } $i++; } ?>
</tr>
答案 0 :(得分:1)
因为我没有看到你的阵列之间有任何关系,但我可以猜到你在寻找什么。
你可能正在寻找第二个数组的
menu_url
和。{ 第一个数组的关键。
为此,您需要在第二个数组中使用$second['menu_url']
。
foreach( $first_array as $key => $value) {
foreach( $second_array as $second ){
if ($second['menu_url'] == $key) {
echo "Hi";
}
}
}
答案 1 :(得分:0)
如果在$ second_array值上检查匹配,请使用以下代码:
foreach( $first_array as $key => $value) {
foreach( $second_array as $second=>$val ) {
foreach($val as $check=>$check_value){
//var_export($check);echo "\n";
//var_export($key);echo "\n";
//var_export($second_array[$second][$check]);echo "\n";
//var_export($second_array[$second][$check] == $key);echo "\n";
//echo"======================= \n";
if ($second_array[$second][$check] == $key) {
echo "Hi";
}
}
}
}
如果只是检查[&#39; menu_url&#39;]匹配array.use此代码:
foreach( $first_array as $key => $value) {
foreach( $second_array as $second ){
if ($second['menu_url'] == $key) {
echo "Hi";
}
}
}