array-flip

PHP array_intersect + array_flip with array that has values multiple times

梦想的初衷 提交于 2019-12-30 11:08:07
问题 I have two arrays: $arr1 = array(101 => 250, 102 => 250, 103 => 250, 104 => 500, 105 => 500, 106 => 500,); and $arr2 = array(0 => 103, 1 => 104, 2 => 105) The result I want to get is Array (103 => 250, 104 => 500) I have tried working with array_intersect(array_flip($arr1), $arr2); but array_flip($arr1) gives something like Array(103 => 250, 106 => 500) thus, keys get lost and can not be intersected correctly. Is there a way to get the desired result? 回答1: The following code does the job. I

array_unique vs array_flip

自闭症网瘾萝莉.ら 提交于 2019-12-17 15:36:07
问题 If I had an array of signed integers e.g: Array ( [0] => -3 [1] => 1 [2] => 2 [3] => 3 [4] => 3 ) To get unique values I would instinctively use array_unique but after consideration I could perform array_flip twice which would have the same effect, and I think it would be quicker? array_unique O(n log n) because of the sort operation it uses array_flip O(n) Am I correct in my assumptions? UPDATE / EXAMPLE: $intArray1 = array(-4,1,2,3); print_r($intArray1); $intArray1 = array_flip($intArray1);

PHP - Make an associative array unique, key -> value and value -> key

放肆的年华 提交于 2019-12-10 17:39:27
问题 I have a little problem in php, which i find hard to explain in words. I have an associative array which contains key-value. I would like to make a function (or if there is already one) which would take an array as input and remove the duplicates but both ways. For example: In my array I have {a -> b} {a -> c} {b -> a} {b -> c} ... From this view it does not seem like there is any duplicate, but to me {a -> b} and {b -> a} are duplicate. So I would like the function to see it as a duplicate

PHP array_intersect + array_flip with array that has values multiple times

邮差的信 提交于 2019-12-01 11:26:29
I have two arrays: $arr1 = array(101 => 250, 102 => 250, 103 => 250, 104 => 500, 105 => 500, 106 => 500,); and $arr2 = array(0 => 103, 1 => 104, 2 => 105) The result I want to get is Array (103 => 250, 104 => 500) I have tried working with array_intersect(array_flip($arr1), $arr2); but array_flip($arr1) gives something like Array(103 => 250, 106 => 500) thus, keys get lost and can not be intersected correctly. Is there a way to get the desired result? The following code does the job. I hope it is self-explanatory. array_unique(array_intersect_key($arr1, array_flip($arr2))) Using the standard