php - Array Intersection - only once -


Newbie here, so I have problems with the array_intersect function I am comparing the intersection of two arrays, but something Results get twice. For example: 2 arrays

  $ array1 = array (apple, orange, orange, apricot, watermelon, watermelon); $ Array2 = array (apple, orange);  

$ result = array_intersect ($ array1, $ array2); This return:

  $ result = array (apple, orange, orange);  

But I want to:

  $ result = array (apple, orange);  

I want it to return to each apple and orange once in a while, it's currently apple, then orange, and then a And gives orange. Am I missing something or I am just using the wrong function.

Edit: Based on the answer I have to make it clear if the second array

  $ array1 = array (apple, orange, orange, Apricots, Watermelon, Watermelon); $ Array2 = array (apple, orange, orange);  

I have 2 oranges, so array_unique is used to do this.

  $ result = array (apple, orange, orange);  

loop through the first array. If the value of the second array is removed then remove the result and the second array.

  $ array1 = array ('apple', 'orange', 'orange', 'apricot', 'watermelon' watermelon); $ Array2 = array ('apple', 'orange'); $ Array3 = array ('apple', 'orange', 'orange'); Function my_intersect ($ array1, $ array2) {// array_walk ($ array1, 'sort'); // array_walk ($ array2, 'sort'); Return array_filter ($ array1, use function ($ item) {if (($ key = array_search ($ item, $ array2)) == false) {unset ($ array2 [$ key] ); Return true;} return false;}); } Var_dump (my_intersect ($ array1, $ array2)); // 'apple', 'orange' var_dump (my_intersect ($ array1, $ array3)); // 'apple', 'orange', 'orange'  

Comments

Popular posts from this blog

sqlite3 - UPDATE a table from the SELECT of another one -

c# - Showing a SelectedItem's Property -

javascript - Render HTML after each iteration in loop -