Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 比较foreach循环中的字符串不会返回正确的数组_Php_Arrays_Foreach_String Comparison - Fatal编程技术网

Php 比较foreach循环中的字符串不会返回正确的数组

Php 比较foreach循环中的字符串不会返回正确的数组,php,arrays,foreach,string-comparison,Php,Arrays,Foreach,String Comparison,我必须创建一个专门的方法来处理如何显示作者姓名。我需要做的是匹配作者角色,并显示主要作者$author和具有相同角色的任何次要作者$author2 在下面的示例中,应该返回的author数组是[Smith,Jones] 输入数组示例: $author = "Smith"; $author2 = ["Jones", "Berry", "Mitchell"]; $auth_role = ""; $auth2_role = [ "", "editor", "editor"]; 现在,该方法只输出主要

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

在下面的示例中,应该返回的author数组是[Smith,Jones]

输入数组示例:

$author = "Smith";
$author2 = ["Jones", "Berry", "Mitchell"];
$auth_role = "";
$auth2_role = [ "", "editor", "editor"];
现在,该方法只输出主要作者$author,而不输出任何其他作者$author2。当我将print语句放入代码中时,它显示它在第一个return语句中返回

到目前为止,我写的方法如下。我认为代码跳过了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;
}
结果:

大堆 [0]=>史密斯 [1] =>琼斯
$over_title和$bibLvl的价值是多少?顺便说一句,你没有用$author2做任何事情。。。至少我希望您尝试访问第一个元素(如果它存在的话)。