gpt4 book ai didi

带数组的 PHP 可选函数参数。如何编码/更好的编码方式?

转载 作者:可可西里 更新时间:2023-11-01 12:40:18 24 4
gpt4 key购买 nike

我相信还有更好的方法。任何帮助将不胜感激。

我想将一个数组传递给包含参数的 php 函数,并且所有参数都是可选的。我正在使用代码点火器,绝不是专家。以下是我到目前为止一直在使用的内容:

function addLinkPost($postDetailArray) {

if (isset($postDetailArray['title'])) {
$title = $postDetailArray['title']; }
else {
$title = "Error: No Title";
}

if (isset($postDetailArray['url'])) {
$url = $postDetailArray['url'];
} else {
$url = "no url";
}
if (isset($postDetailArray['caption'])) {
$caption = $postDetailArray['caption'];
} else {
$caption = "";
}
if (isset($postDetailArray['publish'])) {
$publish = $postDetailArray['publish'];
} else {
$publish = TRUE;
}
if (isset($postDetailArray['postdate'])) {
$postdate = $postDetailArray['postdate'];
} else {
$postdate = "NOW()";
}
if (isset($postDetailArray['tagString'])) {
$tagString = $postDetailArray['tagString'];
} else {
$tagString = "";
}

最佳答案

您可以使用默认值数组,然后将参数数组与默认值合并。如果默认值出现在参数数组中,它们将被覆盖。一个简单的例子:

$defaults = array(
'foo' => 'aaa',
'bar' => 'bbb',
'baz' => 'ccc',
);

$options = array(
'foo' => 'ddd',
);


$merged = array_merge($defaults, $options);

print_r($merged);

/*

Array
(
[foo] => ddd
[bar] => bbb
[baz] => ccc
)

*/

在您的情况下,这将是:

function addLinkPost($postDetailArray) {
static $defaults = array(
'title' => 'Error: No Title',
'url' => 'no url',
'caption' => '',
'publish' => true,
'postdate' => 'NOW()',
'tagString' => '',
);

$merged = array_merge($defaults, $postDetailArray);

$title = $merged['title'];
$url = $merged['url'];
$caption = $merged['caption'];
$publish = $merged['publish'];
$postdate = $merged['postdate'];
$tagString = $merged['$tagString'];
}

关于带数组的 PHP 可选函数参数。如何编码/更好的编码方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1476863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com