PHP : Obtain common values in 2 huge arrays [closed]

試著忘記壹切 提交于 2019-12-25 03:10:18

问题


I have 2 arrays, Array A and B respectively . Array A contains ~300,000 string records, e.g.

[0] => 'apple',
[1] => 'pineapple',
[2] => 'orange',
...
[299,999] => 'banana'

while Array B contains 100,000 string values, e.g.

[0] => 'bamboo',
[1] => 'banana',
[2] => 'boy',
[3] => 'ball',
[4] => 'balloon',
[5] => 'bazooka',

The question is, how to find out the common values between 2 arrays ?

array_intersect() seems a promising function, but I worry about the performance. Is it better to convert the 2 arrays into text file, and do file-based compare? or am I worrying too much?

Codes to use array_intersect():

$result_array = array_intersect($arrayA, $arrayB);

回答1:


Result based on my own test, array_intersect() is the choice. It can produce the result in less than 1 second, as its efficiency is O(n·log n).

Reference: https://stackoverflow.com/a/6329494/188331




回答2:


array_intersect function will be used for retrieving common values across arrays

But as array size is huge you need to specify configuration in script for execution with concern to performance

    set_time_limit(0);
    ini_set('memory_limit','128M');

The above code snippet will respectively set the execution time limit to infinity and increasing memory limit will allocate more memory required to hold large sized array



来源:https://stackoverflow.com/questions/15352507/php-obtain-common-values-in-2-huge-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!