仅保留在指定键处包含指定值的数组行

Only retain array rows which contain a specified value at a specified key

我有这个功能:

function filter($array, $like, $kol) {
    $filtered = array_filter($array, function ($item) use ($kol, $like) {
        return stripos($item[$kol], $like) !== false;
    });
    
    return array_values($filtered);
}

如何将其修改为仅 return 与 $like 一样的精确值?现在它搜索“like $like”。

使用 stripos 将:

Find the numeric position of the first occurrence of needle in the haystack string.

如果你想检查 $item[$kol] 的值是否等于 $like 你可以比较字符串

return $item[$kol] === $like

在对数组进行索引时,您可以先检查键是否存在。

例如

function filter($array, $like, $kol) {
    $filtered = array_filter($array, function ($item) use ($kol, $like) {
        if (array_key_exists($kol, $item)) {
            return $item[$kol] === $like;
        }
        return false;
    });

    return array_values($filtered);
}

Php demo

您的任务是询问如何创建索引数组,其中符合条件的行必须在指定键处包含指定值。

function filter($array, $value, $key) {
    return array_values(
               array_filter(
                   $array,
                   fn($row) => array_key_exists($key, $row) && $row[$key] === $value
               )
           );
}

如果键存在且该键的值完全匹配,array_filter() 调用 returns true(保留行)。