php 数组:每个键存储多个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4488667/
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
array: store multiple values per key
提问by Ahmad Farid
I once trying adding two values with the same key, but it didn't work. It overrode the old value. Isn't it possible to add more than one value with the same key, and when retrieving by key, I get a linked list which I can iterate to get all the different values?
我曾经尝试使用相同的键添加两个值,但没有用。它覆盖了旧值。是否可以使用相同的键添加多个值,并且在通过键检索时,我会得到一个链接列表,我可以通过迭代获取所有不同的值?
采纳答案by cdhowie
Not unless you actually store an array as the value. Hashtables in PHP map a key to onevalue. That value could be an array, but you have to build the array yourself.You might consider creating a class to do this for you.
除非您实际上将数组存储为值,否则不会。PHP 中的哈希表将一个键映射到一个值。该值可以是一个数组,但您必须自己构建该数组。您可以考虑创建一个类来为您执行此操作。
回答by user187291
the simplest option: wherever you use $array[$key]=...
replace it with $array[$key][]=...
最简单的选择:无论您在哪里使用,都$array[$key]=...
将其替换为$array[$key][]=...
回答by Felix Kling
You can create a wrapper function:
您可以创建一个包装函数:
function add_to_array($array, $key, $value) {
if(array_key_exists($key, $array)) {
if(is_array($array[$key])) {
$array[$key][] = $value;
}
else {
$array[$key] = array($array[$key], $value);
}
}
else {
$array[$key] = array($value);
}
}
So you just create a 2-dimensional array. You can retrieve the "linked list" (another array) by normal array access $array[$key]
.
所以你只需创建一个二维数组。您可以通过普通数组访问来检索“链表”(另一个数组)$array[$key]
。
Whether this approach is convenient is up to you.
这种方法是否方便取决于您。