在 foreach 循环中比较字符串不 return 正确的数组

Comparing strings in foreach loop doesn't return correct array

我必须创建一个专门的方法来处理作者姓名的显示方式。我需要做的是匹配作者角色,并显示主要作者 ($author) 和任何具有相同角色的第二作者 ($author2)。

在下面的示例中,应该 returned 的作者数组是 ["Smith", "Jones"].

输入数组示例:

$author = "Smith";
$author2 = ["Jones", "Berry", "Mitchell"];
$auth_role = "";
$auth2_role = [ "", "editor", "editor"];

现在,该方法仅输出主要作者($author),但不输出任何其他作者($author2)。当我将 print 语句放入代码中时,它显示它在第一个 return 语句处 returning 。

目前我写的方法如下。我认为代码正在跳过或跳过 foreach 循环。

/**
 * Get the authors for display.
 *
 * @return array
 */
public function getAuthors()
{
   $leader = $this->marcRecord->getLeader();
   $bibLvl = $leader[7];
   $over_title = $this->fields['item_title_txt'];

   $author2 = $this->getSecondaryAuthors();
   $author = $this->getPrimaryAuthor();
   $auth_role = $this->getPrimaryAuthorRole();
   $auth2_role = $this->getSecondaryAuthorRoles();

   $authdisplay = [$author];

   if (!empty($over_title) && ($bibLvl=='a')) {
    $i=0;
    foreach ($auth2_role as $field){
      if ($field == $auth_role) {
        $authdisplay = [$field];
      }
      $i++;
    }
    return $authdisplay;
  }
  return $authdisplay;
}

关于如何获得正确显示作者列表的方法,您有什么提示吗(即,在上面的示例数组情况下,这将是 ["Smith","Jones"]; )?谢谢。

您需要将 if 替换为:

if (!empty($over_title) && ($bibLvl=='a')) {
    foreach ($auth2_role as $key=>$field){
        if ($field == $auth_role) {
            $authdisplay[] = $author2[$key];
        }
    }
    return $authdisplay;
}

结果:

Array
(
    [0] => Smith
    [1] => Jones
)