PHP:如果键已经存在则附加到值,如果不存在则添加键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1346104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: append to value if the key already exist, if not add the key
提问by Graviton
I am looking for a succinct way of doing this in PHP:
我正在寻找一种在 PHP 中执行此操作的简洁方法:
given an array, if I add one key=>valuepair to it, the routine should check whether the key already exist.
给定一个数组,如果我key=>value向它添加一对,例程应该检查密钥是否已经存在。
If it doesn't exist, add to the array with the key=>valuepair.
如果它不存在,则将其添加到数组中key=>value。
If it does, then the value should be append to the value of the array. So, for example, if the initial array is this
如果是,则该值应附加到数组的值。所以,例如,如果初始数组是这个
arr['a']='2e'
When I add a 'a'=>'45'pair to the array, then the routine will return me
当我'a'=>'45'向数组中添加一对时,例程将返回我
arr['a']=array('2e', '45')
When I add another 'a=>gt'pair to it, then the routine will return me
当我'a=>gt'向它添加另一对时,例程将返回我
arr['a']=array('2e', '45','gt')
Is there a succinct way of doing this? Of course I can write it myself but I believe my solution is very ugly.
有没有一种简洁的方法来做到这一点?当然我可以自己写,但我相信我的解决方案非常难看。
回答by FlorianH
You could solve the problem, by using an array for the first element ("2e") aswell:
您可以通过对第一个元素(“2e”)使用数组来解决这个问题:
$arr = array();
$arr['a'][] = '2e';
$arr['a'][] = '45';
$arr['a'][] = 'gt';
print_r($arr);
回答by VoteyDisciple
There are three situations:
有以下三种情况:
- The key is undefined
- The key is defined, but isn't yet set to an array
- The key is defined, and the element is an array.
- 密钥未定义
- 键已定义,但尚未设置为数组
- 键已定义,元素为数组。
So, in code:
所以,在代码中:
function appendThings(/* map[string,mixed] */ $array, /* string */ $key, /* string */ $value) {
if (!isset($array[$key]))
$array[$key] = $value;
else if (is_array($array[$key]))
$array[$key][] = $value;
else
$array[$key] = array($array[$key], $value);
return $array;
}
It's only the last case that's tricky: if it's not an array yet, you'll need to compose one using the current value plus the new one.
只有最后一种情况很棘手:如果它还不是数组,则需要使用当前值加上新值组合一个。
回答by Amber
function update_keypair($arr, $key, $val)
{
if(empty($arr[$key])) $arr[$key] = array($val);
else $arr[$key][] = $val;
}
does exactly what you want.
做你想要的。
回答by n1313
if (isset($array[$key]) {
if (!is_array($array[$key]))
$array[$key] = (array)$array[$key];
$array[$key][] = $new_value;
} else {
$array[$key] = $new_value;
}
Something like that? You can surely simplify this by adding first value as an one-element array, or by using ternar operators, but anyway you'll need a custom function to do the job.
类似的东西?您当然可以通过将第一个值添加为单元素数组或使用三元运算符来简化此操作,但无论如何您都需要一个自定义函数来完成这项工作。
回答by Quamis
Strictly array:
严格数组:
$arr['a']=(is_array($arr['a'])? '2e' : array_merge(Array('2e'),$arr['a']));
String with separators:
带分隔符的字符串:
$arr['a'].='2e'.'/'; // '/' is used as a separator in here.
if you need the string as an array just do $arr['a'] = explode("/",$arr['a']);
如果你需要字符串作为数组就做 $arr['a'] = explode("/",$arr['a']);
both methods are ugly... you should try, as FlorianH suggested, to use the whole variable as an array.
这两种方法都很丑陋......你应该尝试,正如 FlorianH 建议的那样,将整个变量用作数组。
Another method might be to use the Interface in PHp and build something that make suse of the Iterator and ArrayAccess interfaces. (http://us3.php.net/manual/en/class.iterator.php, http://us3.php.net/manual/en/class.arrayaccess.php)
另一种方法可能是使用 PHp 中的接口并构建一些使用 Iterator 和 ArrayAccess 接口的东西。( http://us3.php.net/manual/en/class.iterator.php, http://us3.php.net/manual/en/class.arrayaccess.php)
回答by RaYell
You need to write a function that does that. Or initialize your first element as an array as well and use array_push function to add new elements.
您需要编写一个执行此操作的函数。或者也将您的第一个元素初始化为数组并使用 array_push 函数添加新元素。
$a = array('2e');
array_push($a, '45');
array_push($a, 'gt');
回答by mck89
Try this
尝试这个
$key="a";
$value="b";
$array=array();
if(!array_key_exists($key,$array)) $array[$key]=$value;
elseif(is_array($array[$key]))$array[$key][]=$value;
else $array[$key]=array($array[$key],$value);

