函数仅返回第一个数组
我正在尝试向 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" => ""
);
}
}
I'm trying to add some settings to my WordPress options page that depend on the number of categories. I created this function to use inside the main array, but it only returns the first array, leaving out the other 3 I have. A print_r
will show all of them, so I can't seem to figure this out.
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" => ""
);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您只能返回一次!
修复方法是将每个数组推入临时数组,然后在循环结束时返回该数组。
You can only return once!
The fix is push each array into a temporary array, then return that array at the end of the loop.
该函数只能返回一次。它不能在循环中返回多个内容。到达第一次返回后,它完全退出该函数。如果你想返回一个数组的数组,你应该使用以下内容。
使用语法 $result[] = xyz;将把 xyz 添加到数组的末尾。您可以使用类似的代码循环返回的数组
The function can only return once. It cannot return multiple things in a loop. After it reaches the first return, it exits the function completely. If you want to return an array of arrays, you should use the following.
using the syntax $result[] = xyz; will append xyz to the end of the array. You can loop through the returned array, with some code like
当您从函数中调用 return 时,它总是立即结束该函数的执行,因此一旦返回第一个数组,函数就会结束 - 这就是为什么您只返回第一个数组的原因。
您可以尝试返回一个多维数组(一个包含您想要返回的所有数组的数组)。
When you call
return
from a function it always immediately ends the execution of that function, so as soon as the first array gets returned, the function ends - which is why you are only getting the first array back.You could try returning a multi-dimensional array (an array that contains all of the arrays you'd like to be returned) instead.
return
关键字的目标是退出函数。所以你的函数只返回第一个元素是正常的。例如,您可以将所有元素放入一个数组中并返回该数组:
The goal of the
return
keyword is to exit the function. So it is normal that your fonction only return the first element.You can for exemple put all the elements into an array and return this array :