从二维数组中的列获取唯一值
我有一个二维数组,需要将唯一的列与一列隔离开。
$array = [
[..., 'key' => 1, ...],
[..., 'key' => 2, ...],
[..., 'key' => 3, ...],
[..., 'key' => 1, ...],
[..., 'key' => 2, ...],
[..., 'key' => 3, ...],
[..., 'key' => 4, ...],
[..., 'key' => 5, ...],
[..., 'key' => 6, ...]
];
仅当元素尚不存在时,如何将它们添加到结果数组中?我有以下内容:
$a = [];
// organize the array
foreach ($array as $k => $v) {
foreach ($v as $key => $value) {
if ($key == 'key') {
$a[] = $value;
}
}
}
print_r($a);
输出:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 1
[4] => 2
[5] => 3
[6] => 4
[7] => 5
[8] => 6
)
相反,我希望 $a
由唯一值组成。 (我知道我可以在循环后使用 array_unique() 来获得所需的结果,但我只想知道任何其他方法。)
I have a 2d array and need to isolate the unique columns from one column.
$array = [
[..., 'key' => 1, ...],
[..., 'key' => 2, ...],
[..., 'key' => 3, ...],
[..., 'key' => 1, ...],
[..., 'key' => 2, ...],
[..., 'key' => 3, ...],
[..., 'key' => 4, ...],
[..., 'key' => 5, ...],
[..., 'key' => 6, ...]
];
How do I add elements to the result array only if they aren't in there already? I have the following:
$a = [];
// organize the array
foreach ($array as $k => $v) {
foreach ($v as $key => $value) {
if ($key == 'key') {
$a[] = $value;
}
}
}
print_r($a);
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 1
[4] => 2
[5] => 3
[6] => 4
[7] => 5
[8] => 6
)
Instead, I want $a
to consist of the unique values. (I know I can use array_unique()
after looping to get the desired results, but I just want to know of any other ways.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(16)
您应该使用 PHP 函数
in_array
(请参阅 http:// /php.net/manual/en/function.in-array.php)。这是文档中关于
in_array
的内容:You should use the PHP function
in_array
(see http://php.net/manual/en/function.in-array.php).This is what the documentation says about
in_array
:您必须对照 in_array 检查每个值:
You'd have to check each value against in_array:
由于您似乎只有 标量值 PHP 的数组更像是一个哈希映射,因此您可以使用value 作为键以避免重复并将
$k
键关联到它们以便能够获取原始值:然后您只需迭代它即可获取原始值:
这可能不是最明显的也是最全面的方法,但它非常高效,因为它的时间复杂度为 O(n)。
像其他人建议的那样使用
in_array
可能更直观。但是您最终会得到 O(n2) 的算法(in_array
的时间复杂度为 O(n) ) 不适用。即使推送数组中的所有值并使用array_unique
也会比in_array
(array_unique
对 O(n·log n) 中的值进行排序,然后删除连续的重复项)。Since you seem to only have scalar values an PHP’s array is rather a hash map, you could use the value as key to avoid duplicates and associate the
$k
keys to them to be able to get the original values:Then you just need to iterate it to get the original values:
This is probably not the most obvious and most comprehensive approach but it is very efficient as it is in O(n).
Using
in_array
instead like others suggested is probably more intuitive. But you would end up with an algorithm in O(n2) (in_array
is in O(n)) that is not applicable. Even pushing all values in the array and usingarray_unique
on it would be better thanin_array
(array_unique
sorts the values in O(n·log n) and then removes successive duplicates).易于编写,但不是最有效的:
这个可能更快:
Easy to write, but not the most effective one:
This one is probably faster:
尝试添加为键而不是值:
添加条目
获取所有条目
Try adding as key instead of value:
Adding an entry
Getting all entries
如果您可以在代码中使用简写(而不是像某些编码标准推荐的那样编写明确的
if
块),您可以进一步用这句话简化Marius Schulz的答案:If you're okay with using shorthands in your code (instead of writing explicit
if
blocks, like some coding standards recommend), you can further simplify Marius Schulz's answer with this one-liner:如果您不关心键的顺序,可以执行以下操作:
If you don't care about the ordering of the keys, you could do the following:
由于有很多方法可以实现所需的结果,并且很多人提供了
!in_array()
作为答案,并且 OP 已经提到了array_unique
的使用,我我想提供几个替代方案。使用
array_diff
(php >= 4.0.1 || 5) 您可以仅过滤掉不存在的新数组值。或者,您也可以使用 array_diff_assoc 来比较键和值。 http://php.net/manual/en/function.array-diff.php结果:
http://ideone.com/SWO3D1
另一种方法是使用
array_flip 将值分配为键并使用
isset
进行比较,对于大型数据集,这将比in_array
执行得更快。同样,这仅过滤掉当前值中尚不存在的新值。结果:
http://ideone.com/cyRyzN
无论使用哪种方法,您都可以使用
array_merge
将唯一的新值附加到当前值。结果:
Since there are a ton of ways to accomplish the desired results and so many people provided
!in_array()
as an answer, and the OP already mentions the use ofarray_unique
, I would like to provide a couple alternatives.Using
array_diff
(php >= 4.0.1 || 5) you can filter out only the new array values that don't exist. Alternatively you can also compare the keys and values witharray_diff_assoc
. http://php.net/manual/en/function.array-diff.phpResult:
http://ideone.com/SWO3D1
Another method is using
array_flip
to assign the values as keys and compare them usingisset
, which will perform much faster thanin_array
with large datasets. Again this filters out just the new values that do not already exist in the current values.Result:
http://ideone.com/cyRyzN
With either method you can then use
array_merge
to append the unique new values to your current values.Result:
您可以尝试使用“in_array”:
you can try using "in_array":
采用 Gumbo 的想法,使代码正常工作:
给出:
Taking Gumbo's idea, making the code work:
Gives this:
使用
array_flip()
,它可能看起来像这样:使用
array_unique()
- 像这样:注意
array_values(...)
- 如果您要将数组以 JSON 形式导出到 JavaScript,则需要它。仅array_unique()
会简单地取消重复键的设置,而无需重建剩余元素。因此,转换为 JSON 后将生成对象,而不是数组。With
array_flip()
it could look like this:With
array_unique()
- like this:Notice that
array_values(...)
— you need it if you're exporting array to JavaScript in JSON form.array_unique()
alone would simply unset duplicate keys, without rebuilding the remaining elements'. So, after converting to JSON this would produce object, instead of array.要从二维数组中的单列标量值填充唯一值的平面索引数组,您可以使用 array_column() 并将第二个和第三个参数指定为同一所需列。
由于 PHP 不允许数组同一级别上的键重复,因此您将获得所需的唯一值结果。
这种技术是可靠的,因为被隔离的值在用作键时不会被 PHP 改变——对于空值、浮点数、布尔值和更多数据类型来说,情况并非如此。
仅当您想重新索引键时才需要 array_values() ;否则,您可以保留临时键并避免额外的函数调用。
代码:(Demo)
输出:
为了实现迭代的语言构造,您可以使用无体
foreach()
并访问key
列值两次,以将关联值推入结果数组。 演示主题阅读:解构数组时,是否可以多次访问同一个元素值?
To populate a flat, indexed array of unique values from a single column of scalar values from a 2d array, you can use
array_column()
and nominate the 2nd and 3rd parameters as the same desired column.Because PHP doesn't allow keys on the same level of an array to be duplicated, you get the desired unique value results.
This technique is reliable because none of the values being isolated will be mutated by PHP upon being used as keys -- this is not true of nulls, floats, booleans, and more data types.
array_values()
is only necessary if you want to re-index the keys; otherwise you can leave the temporary keys and avoid the extra function call.Code: (Demo)
Output:
For the implementation of a language construct for iteration, you can use a body-less
foreach()
and access thekey
column value twice to push associative values into the result array. DemoTopical reading: While destructuring an array, can the same element value be accessed more than once?
您还可以使用 +=
将导致 $options1 等于:
其中 as
将导致 $options2 等于:
You can also use +=
will result in $options1 equal to:
where as
will result in $options2 equal to:
试试这个代码,我从 得到它这里
Try this code, I got it from here