【问题标题】:Return more than one result from a function [duplicate]从函数返回多个结果[重复]
【发布时间】:2019-07-31 04:55:48
【问题描述】:

这是我列出所有角色的脚本...

function all_the__roles() {
    global $wp_roles;
    $the_roles = $wp_roles->get_names();
    $roles = '';
    $role_count = '';
    foreach($the_roles as $role) {
        $roles .= $role . '<br />';
        $role_count++;
    }
    return $roles;
}

echo all_the__roles();

如果我将return $roles; 更改为return $role_count;,那么我会得到角色的数量。

有没有一种方法可以在不编写额外的单独函数的情况下同时拥有两者?我想列出角色还有数字角色。所以输出可能是这样的:

Administrator
Editor
Client
3

干杯。

【问题讨论】:

  • 就我个人而言,我不会为这个函数而烦恼,你可以做$the_roles = $wp_roles-&gt;get_names();,然后做implode('&lt;br&gt;', $the_roles )count($the_roles) 等。然后没有理由为它创建一个函数。否则执行return ['roles' =&gt; implode('&lt;br&gt;', $the_roles ), 'count' =&gt; count($the_roles)] 并删除foreach -6 行代码。

标签: php wordpress loops count roles


【解决方案1】:

请试试这个

function all_the__roles() {
    global $wp_roles;
    $the_roles = $wp_roles->get_names();
    $roles = '';
    $role_count = 0;
    foreach($the_roles as $role) {
        $roles .= $role . '<br />';
        $role_count++;
    }

    if($role_count > 0){
        $roles .= $role_count . '<br />';
    }

    return $roles;
}

echo all_the__roles();

【讨论】:

  • 这行得通,但这不是我所需要的。我可能可以更好地解释它。在文档的某个地方我可能想列出角色,而在文档的其他地方我可能想显示角色的数量。因此,我需要该功能为我提供一种在文档的任何部分中执行任一操作的方法。
  • 是的,试试这个函数 all_the__roles() { global $wp_roles; $the_roles = $wp_roles->get_names(); $role_count = 0; $数据 = 数组(); foreach($the_roles as $role) { $data['roles'][] = $role; $role_count++; } if($role_count > 0){ $data['roles'] = $role_count; } 返回$数据; } print_r(all_the__roles());
  • 他们只需要这个function all_the__roles() { global $wp_roles; $the_roles = $wp_roles-&gt;get_names(); return ['roles' =&gt; implode('&lt;br&gt;', $the_roles ), 'count' =&gt; count($the_roles)]; }
  • 函数 all_the__roles() { 全局 $wp_roles; $the_roles = $wp_roles->get_names(); $role_count = 0; $数据 = 数组(); foreach($the_roles as $role) { $data['roles'][] = $role; $role_count++; } if($role_count > 0){ $data['roles_count'] = $role_count; } 返回$数据; } $roles_data = all_the__roles(); $roles = $roles_data['roles']; // 或 $roles = implode("
    ",$roles); $roles_count = $roles_data['roles_count'];
猜你喜欢
  • 2017-11-19
  • 2012-02-14
  • 2020-05-11
  • 2011-04-19
  • 2010-10-19
  • 1970-01-01
  • 2019-09-17
相关资源
最近更新 更多