gpt4 book ai didi

php - 如何格式化一个简单的 PHP 字符串数组?

转载 作者:可可西里 更新时间:2023-11-01 00:38:31 24 4
gpt4 key购买 nike

我有一个简单的函数,我传入一个字符串数组:

function myfunction( $arg = array() )
{
// do stuff to $arg...
// return a $string;
}

到目前为止很简单,但我需要 $arg 数组中的一些字符串被格式化,而一些保持未格式化。我不知道该怎么做?

假设我通过 myfunction() 运行此 $arg:

echo myfunction( array( 'format me!', 'do not format me!' ) );

我的小脑袋不知道如何告诉 myfunction() $arg 数组中的第一个值需要格式化,而它不应该格式化第二个值。

我考虑过关联数组,但我认为这可能是错误的方法,因为它具有相同的索引。

echo myfunction( array( 'format' => 'hi', 'format' => 'bye', 'noformat' => 'foo');

只是在寻找正确方向的“插入”。

编辑 1:

忘了说,我只能有一个 $arg 数组,因为我需要键按特定顺序排列。

编辑 2:

$arg 数组可以有用户想要的任意多个键。

最佳答案

你可以这样做:

function myfunction(array $format, array $noformat) {
...
}

function myfunction(array $strings) {
foreach ($strings['format'] as $format) {
// do stuff
}
foreach ($strings['noformat'] as $noformat) {
// do stuff
}
}

与:

myfunction(array(
'format' => array('one', 'two', 'three'),
'noformat' => array('four', 'five', 'six'),
));

如果(且仅当)字符串唯一,您可以将它们放在键中而不是值中:

$strings = array(
'one' => true,
'two' => false,
'three' => false,
'four' => true,
);

myfunction($strings);

与:

function myfunction(array $strings) {
foreach ($strings as $k => $v) {
if ($v) {
// format string
}
}
}

但是因为你不能有重复的键,如果你有重复的字符串,这个方法就会失败。

关于php - 如何格式化一个简单的 PHP 字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1999532/

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