PHP 函数语法错误,不知道为什么

PHP syntax error in function, don't know why

我遇到了语法错误,我不知道为什么。 "Parse error: syntax error, unexpected '{' on line 6"

function ExtractCustomField($fieldName, $customFields) {
// $customFields might be an object, NULL, or an array.
$parsed = array();
if (is_array($customFields) == false && $customFields != null) {
$parsed = array($customFields);
} else (is_array($customFields)) {
$parsed = $customFields;
}

// loop through the fields and find the one we are looking for
$returnField = null;
foreach($field as $customFields) {
if ($field->Name == $fieldName) {
$returnField = $field;
break;
}
}

return $returnField
}

else 后面没有任何表达式。删除表达式或改用 elseif

您在 return

中漏掉了分号
return $returnField;
}

还有 Else 条件 else (is_array($customFields)) 格式错误....否则不要在它后面加上任何条件...您可以改用 Elseif

else (is_array($customFields)) {

无效。使用 else if 或删除条件

function ExtractCustomField($fieldName, $customFields) {
// $customFields might be an object, NULL, or an array.
$parsed = array();
if (is_array($customFields) == true && $customFields != null) {
$parsed = array($customFields);
} else {
$parsed = $customFields;
}

// loop through the fields and find the one we are looking for
$returnField = null;
foreach($field as $customFields) {
if ($field->Name == $fieldName) {
$returnField = $field;
break;
}
}

return $returnField;
}

你忘了在 $returnField 后面加分号,也用 elseif 代替 else(else 不需要任何参数)。使用下面的代码

function ExtractCustomField($fieldName, $customFields) {
// $customFields might be an object, NULL, or an array.
$parsed = array();
if (is_array($customFields) == false && $customFields != null) {
$parsed = array($customFields);
} elseif (is_array($customFields)) {
$parsed = $customFields;
}

// loop through the fields and find the one we are looking for
$returnField = null;
foreach($field as $customFields) {
if ($field->Name == $fieldName) {
$returnField = $field;
break;
}
}

return $returnField;
}

希望对您有所帮助

否则应该是 if(is_array($customFields)) 或 elseif(is_array($customFields))

我已经修改了你的函数,我看到应该是 elseif 而不是 else 并且在 foreach 循环中,你的代码中的语法是错误的。我还假设您将使用单级关联数组。

<?php
    function ExtractCustomField($fieldName, $customFields) {
            // $customFields might be an object, NULL, or an array.
            $parsed = array();
            if (is_array($customFields) == false && $customFields != null) {
                $parsed = array($customFields);
            } elseif (is_array($customFields)) {
                $parsed = $customFields;
            }

            // loop through the fields and find the one we are looking for
            $returnField = null;
            foreach($customFields as $field) {
                if ($field == $fieldName) {
                    $returnField = $field;
                    break;
                }
            }
            return $returnField;
        }

        echo ExtractCustomField('name', array('name','emial','mobile','password'));
?>