如果不在其他数组中,则从数组中删除值,但保持相同的顺序
Posted
技术标签:
【中文标题】如果不在其他数组中,则从数组中删除值,但保持相同的顺序【英文标题】:Remove values from array if not in other array, but keeping same order 【发布时间】:2011-07-04 07:27:33 【问题描述】:我有两个数组:
$array1:
Array
(
[0] => 2032
[1] => 2027
[2] => 2025
[3] => 2023
[4] => 2021
[5] => 2018
[6] => 2014
[7] => 2011
[8] => 2009
[9] => 1947
[10] => 1941
[11] => 1939
[12] => 1937
[13] => 1935
[14] => 1933
[15] => 1928
[16] => 1926
[17] => 1924
[18] => 1922
[19] => 1920
[20] => 1918
[21] => 1916
[22] => 1910
[23] => 1881
[24] => 1680
[25] => 1678
[26] => 1879
[27] => 1877
[28] => 1875
[29] => 1873
[30] => 1871
[31] => 1869
[32] => 1865
[33] => 1863
[34] => 1858
[35] => 1850
[36] => 1844
[37] => 1838
[38] => 1829
[39] => 1827
[40] => 1825
[41] => 1821
[42] => 1819
[43] => 1814
[44] => 1812
[45] => 1810
[46] => 1808
[47] => 1806
[48] => 1804
[49] => 1801
[50] => 1793
[51] => 1791
[52] => 1789
[53] => 1784
[54] => 1774
[55] => 1772
[56] => 1770
[57] => 1768
[58] => 1766
[59] => 1764
[60] => 1762
[61] => 1760
[62] => 1754
[63] => 1748
[64] => 1746
[65] => 1744
[66] => 1740
[67] => 1738
[68] => 1732
[69] => 1722
[70] => 1720
[71] => 1716
[72] => 1714
[73] => 1711
[74] => 1708
[75] => 1703
[76] => 1699
[77] => 1673
[78] => 1671
[79] => 1669
[80] => 1667
[81] => 1665
[82] => 1663
[83] => 1661
[84] => 1659
[85] => 1655
)
$array2:
Array
(
[0] => 1665
[1] => 1671
[2] => 1714
[3] => 1716
[4] => 1722
[5] => 1732
[6] => 1774
[7] => 1801
[8] => 1804
[9] => 1916
[10] => 1918
[11] => 1920
[12] => 1924
[13] => 1933
[14] => 1935
[15] => 1939
)
我需要做的是检查数组 1 的每个值,看看它是否在数组 2 中,如果值在数组 2 中,则将该值放入数组 3 中。但是数组 3 需要保持数组 1 中值出现的顺序。
我可以编写一些代码来循环遍历数组 1,执行 in_array(),如果为 true,则放入数组 3。这可行,但我提出问题的原因是是否有任何功能可用于此任务?如果没有,那么最有效和最快速的方法是什么?
【问题讨论】:
【参考方案1】:你可以使用 array_intersect()。
http://php.net/manual/en/function.array-intersect.php
【讨论】:
【参考方案2】:$array3 = array_intersect($array, $array2)
http://php.net/manual/en/function.array-intersect.php
【讨论】:
以上是关于如果不在其他数组中,则从数组中删除值,但保持相同的顺序的主要内容,如果未能解决你的问题,请参考以下文章
如果重复 x 次,则从数组中删除值 | JavaScript
如果numpy数组的所有元素都等于某个值,则从numpy数组中删除行/列