PHP嵌套“的foreach”循环只使用数组
问题描述:
的最后一个值我写了下面的循环创建WordPress的自定义控件更快:PHP嵌套“的foreach”循环只使用数组
<?php
/* Creates "Color Scheme" section */
$wp_customize->add_panel('color_scheme', array(
'title' => 'Color Scheme',
'priority' => 120,
));
/* Creates "Navbar" section */
$wp_customize->add_section('navbar', array(
'title' => 'Navbar',
'description' => '',
'priority' => 120,
'panel' => 'color_scheme'
));
/* Navbar Color Controls */
$color_controls = array("menu-bg-color", "menu-button-color", "menu-site-title-color", "menu-overlay-bg-color", "menu-items-color");
$color_labels = array("Background Color", "Button Color", "Title Color", "Overlay Background Color", "Overlay Item Color");
foreach($color_controls as $control) {
foreach($color_labels as $label) {
$wp_customize->add_setting($control);
$wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, $control, array(
'label' => $label,
'section' => 'navbar',
'settings' => $control
)));
}
}
?>
这是结果:Screenshot of my WordPress customizer 它不是通过标签和唯一的循环使用最后一个值。
答
$color_controls = array(
"menu-bg-color" => "Background Color",
"menu-button-color" => "Button Color",
"menu-site-title-color" => "Title Color",
"menu-overlay-bg-color" => "Overlay Background Color",
"menu-items-color" => "Overlay Item Color"
);
foreach ($color_controls as $control => $label) {
$wp_customize->add_setting($control);
$wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, $control, array(
'label' => $label,
'section' => 'navbar',
'settings' => $control
)));
}
我想这就是你要找的。嵌套循环用于当array1中的每个项目需要array2中的每个项目时。您实际上需要一个关键字和值的关联数组,并循环遍历它们,其中键是映射到标签值的控件。
+0
这个工程!非常感谢你向我展示什么是关联数组!这对我来说是一场游戏改变! –
你确定你想要一个嵌套循环吗?您的控件和标签似乎以1:1匹配。你想要一个带有“背景颜色”标签的控件“menu-bg-color”...用“按钮颜色”标签控制“菜单按钮颜色”等等,对吧? –
是的,我希望我的控件和标签能够匹配。我想我想要一个嵌套循环,但如果有更好的方法来做到这一点,我肯定想学习如何。 –