如何将 2 维字符串数组转换为 1 维修剪后的唯一值数组?
我有一个数组,其值都是特定格式的数组,如下所示:
Array
(
[0] => Array
(
[0] => '8227'
[1] => ' 8138'
)
[1] => Array
(
[0] => '8227'
[1] => ' 8138'
[2] => ' 7785'
)
)
我想要这个:
Array
(
[0] => 8227
[1] => 8138
[2] => 7785
)
我该怎么做?
I have an array whose values are all arrays of a specific format that looks like this:
Array
(
[0] => Array
(
[0] => '8227'
[1] => ' 8138'
)
[1] => Array
(
[0] => '8227'
[1] => ' 8138'
[2] => ' 7785'
)
)
and I would like to have this:
Array
(
[0] => 8227
[1] => 8138
[2] => 7785
)
How can I do this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
array_merge_recursive()
可用于展平数组。然后,array_unique()
获取唯一值,使用array_values()
来“重新索引”结果数组。array_merge_recursive()
can be used to flatten the array. Then,array_unique()
to get the unique values, witharray_values()
to "reindex" the resultant array.我不喜欢迭代调用
in_array()
的想法,因为它可能会对大数组造成一些阻力。现在,我遵循的方法可能不会设置任何速度记录(我没有费心进行基准测试),但我想我会发布一些非正统的方法,以防它们激发未来的读者。
方法#1:
array_keys()
(输出值为整数类型)方法#2:
array_flip()
消除重复array_keys()
重新索引结果数组(输出值是整数类型)代码:(Demo)
输出:
如果这些方法中的任何一个执行良好,那将是因为它们不进行迭代函数调用。
ps 好吧,因为我很好奇,我只是对我的两种方法和 DaveRandom 的方法做了一个非常小的/非官方的速度测试(仅使用 OP 的数据进行了 1000 次迭代 - 我不想滥用 3v4l.org)和...
再次,我将声明,为微优化而制造的测试可能毫无意义,如果它确实很重要,则应该对您的真实数据进行真正的测试。如果您只是喜欢本页上另一个答案的逻辑流程,我完全尊重这一点。
I don't like the idea of iterated calls of
in_array()
since it can cause a bit of drag on big arrays.Now, my methods to follow are probably not going to set any speed records (I didn't bother to benchmark), but I thought I would post a couple of unorthodox approaches in case they may inspire future readers.
Method #1:
array_flip()
array_keys()
(output values are integer-type)Method #2:
array_flip()
array_keys()
(output values are integer-type)Code: (Demo)
Output:
If either of these methods perform well, it will be because they don't make iterated function calls.
p.s. Okay, because I was curious, I just did a very small / unofficial speed test on my two methods and DaveRandom's method (only 1000 iterations using the OP's data - I didn't want to abuse 3v4l.org) and...
Again, I'll state that fabricated tests for micro-optimization may be pointless and real tests should be done on your REAL data IF it is actually important. If you merely prefer the logical flow of another answer on this page, I totally respect that.