PHP array_search for multi dimensional array and return key

后端 未结 3 1482
误落风尘
误落风尘 2021-01-25 02:25

I\'m trying to search for a value in a multi dimensional array (below is only a part of the big array) and get the key for that value but I can\'t manage it by myself. Here is w

3条回答
  •  渐次进展
    2021-01-25 03:21

    If you don't need to key, you could use array_filter

    $result = array_filter($data, function($item) use ($search) {
        return $item[8] == $search;
    })[0];
    

    If you need the key, you could modify it like this

    $key = false;
    $result = array_filter($data, function($item, $k) use ($search, &$key) {
        if ($item[8] == $search) {
            $key = $k;
            return true;
        }
        return false;
    }, ARRAY_FILTER_USE_BOTH)[0];
    

    To handle cases, where no result is found, you have to skip the [0] party and test if count($result) != 0

提交回复
热议问题