开发者

How do I make a new array containing just one instance of duplicates from 2 separate arrays while combining them in php?

开发者 https://www.devze.com 2023-03-28 01:10 出处:网络
So far I have done the following: $row = mysql_fetch_assoc($result); $row2 = mysql_fetch_assoc($result);

So far I have done the following:

$row = mysql_fetch_assoc($result);
$row2 = mysql_fetch_assoc($result);
$duplicates = array_intersect($row, $row2);

How do I combine the 2 arrays and make a new one that just contains one instance of the previously repeated variables? (so if array $row contained the variable 'apple' 2 times and the array $row2 contained the variable 'apple' 3 times, in the new, merged array, 'apple' would only appear once.

edit: I didn't realize that the array_merge() function works differently for num开发者_运维问答bers than compared to strings. I gave the 'apple' example above but my arrays are dealing with product IDs which are numbers. PHP manual says

If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

and I need help in merging arrays with numbers, what should I do?


You can use

$c = array_merge($a, $b);

http://php.net/manual/en/function.array-merge.php

if you want to remove duplicate values after the merge then use array_unique();

so...

$c = array_unique(array_merge($a, $b));
0

精彩评论

暂无评论...
验证码 换一张
取 消