Check if a specific value exists at a specific key in any subarray of a multidimensional array

前端 未结 13 2201
梦毁少年i
梦毁少年i 2020-11-27 18:42

I need to search a multidimensional array for a specific value in any of the indexed subarrays.

In other words, I need to check a single column of the multidimension

13条回答
  •  Happy的楠姐
    2020-11-27 19:27

    TMTOWTDI. Here are several solutions in order of complexity.

    (Short primer on complexity follows):O(n) or "big o" means worst case scenario where n means the number of elements in the array, and o(n) or "little o" means best case scenario. Long discrete math story short, you only really have to worry about the worst case scenario, and make sure it's not n ^ 2 or n!. It's more a measure of change in computing time as n increases than it is overall computing time. Wikipedia has a good article about computational aka time complexity.

    If experience has taught me anything, it's that spending too much time optimizing your programs' little-o is a distinct waste of time better spent doing something - anything - better.

    Solution 0: O(n) / o(1) complexity:

    This solution has a best case scenario of 1 comparison - 1 iteration thru the loop, but only provided the matching value is in position 0 of the array. The worst case scenario is it's not in the array, and thus has to iterate over every element of the array.

    foreach ($my_array as $sub_array) {
        if (@$sub_array['id'] === 152) {
            return true;
        }
    }
    return false;
    

    Solution 1: O(n) / o(n) complexity:

    This solution must loop thru the entire array no matter where the matching value is, so it's always going to be n iterations thru the array.

    return 0 < count(
        array_filter(
            $my_array,
            function ($a) {
                return array_key_exists('id', $a) && $a['id'] == 152;
            }
        )
    );
    

    Solution 2: O(n log n) / o(n log n) complexity:

    A hash insertion is where the log n comes from; n hash insertions = n * log n. There's a hash lookup at the end which is another log n but it's not included because that's just how discrete math works.

    $existence_hash = [];
    foreach ($my_array as $sub_array) {
        $existence_hash[$sub_array['id']] = true;
    }
    return @$existence_hash['152'];
    

提交回复
热议问题