我正在尝试将一些设置添加到我的WordPress选项页面,这取决于类别的数量。我创建了这个函数以在主数组中使用,但它只返回第一个数组,而忽略了我拥有的其他3个数组。 print_r
会显示所有这些,所以我似乎无法弄清楚这一点。
function listSections() {
$categories = get_categories();
foreach($categories as $category) {
return array (
"name" => $category->cat_name . " Label Color",
"desc" => "Select a label color.",
"id" => $shortname."_label_color" . $category->cat_ID,
"type" => "select",
"options" => $color_options,
"std" => ""
);
}
}
答案 0 :(得分:4)
你只能回来一次!
function listSections() {
$categories = get_categories();
$return = array();
foreach($categories as $category) {
$return[] = array (
"name" => $category->cat_name . " Label Color",
"desc" => "Select a label color.",
"id" => $shortname."_label_color" . $category->cat_ID,
"type" => "select",
"options" => $color_options,
"std" => ""
);
}
return $return;
}
修复程序将每个数组推送到一个临时数组中,然后在循环结束时返回该数组。
答案 1 :(得分:1)
该功能只能返回一次。它不能在循环中返回多个东西。到达第一次返回后,它完全退出该功能。如果要返回数组数组,则应使用以下内容。
function listSections() {
$results = array();
$categories = get_categories();
foreach($categories as $category) {
$results[] = array (
"name" => $category->cat_name . " Label Color",
"desc" => "Select a label color.",
"id" => $shortname."_label_color" . $category->cat_ID,
"type" => "select",
"options" => $color_options,
"std" => ""
);
}
return $results;
}
使用语法$ result [] = xyz;将xyz附加到数组的末尾。您可以使用某些代码(例如
)遍历返回的数组$results = listSections();
$count = count($results);
for ($i = 0; $i < $count; $i++) {
$category = $results[$i];
echo $category["name"];
etc......
}
答案 2 :(得分:0)
当你从一个函数调用return
时,它总是立即结束该函数的执行,因此只要第一个数组返回,函数就会结束 - 这就是为什么你只得到第一个数组。
你可以尝试返回一个多维数组(一个包含你想要返回的所有数组的数组)。
答案 3 :(得分:0)
return
关键字的目标是退出该功能。所以你的功能只返回第一个元素是正常的。
例如,您可以将所有元素放入数组中并返回此数组:
function listSections() {
$categories = get_categories();
$arr = array();
foreach($categories as $category) {
$arr[] = array (
"name" => $category->cat_name . " Label Color",
"desc" => "Select a label color.",
"id" => $shortname."_label_color" . $category->cat_ID,
"type" => "select",
"options" => $color_options,
"std" => ""
);
}
return $arr;
}