如果value在数组的第二维中,则返回true

时间:2018-01-27 09:22:44

标签: php arrays

我有一个数组:

( 
   [0] => Array ( [category] => Category 1 ) 
   [1] => Array ( [category] => Category 2 ) 
   [2] => Array ( [category] => Category 3 ) 
)

我想为函数提供一个值,如果该值是现有类别,则返回true。

例如:

function valueExists($key, $value) {
    // Function code
    if () {
        return true;
    } else {
        return false;
    }
}

if (valueExists("category", "Category 2")) {
    echo "Category 2 is found in array."
} else {
    echo "Category 2 not found in array."
}

我如何遍历每个数组(基于第二维)并创建此函数?

3 个答案:

答案 0 :(得分:2)

$arr = [
   ['category' => 'Category 1'], 
   ['category' => 'Category 2'], 
   ['category' => 'Category 3'], 
];

// true or false
in_array('Category 2', array_column($arr, 'category'));

答案 1 :(得分:0)

您可以尝试这样的事情:

// add $arr parameter to pass the array you want to check.
function valueExists($arr, $key, $value) {
    foreach ($arr as $item) {
        if (isset($item[$key]) && $item[$key] == $value) {
            return true;
        }
    } 
    return false;
}


$arr = [
   ['category' => 'Category 1'], 
   ['category' => 'Category 2'], 
   ['category' => 'Category 3'], 
];


if (valueExists($arr, "category", "Category 2")) {
    echo "Category 2 is found in array.";
} else {
    echo "Category 2 not found in array.";
}

输出:

  

在数组中找到类别2.

答案 2 :(得分:0)

$catArr = [
   ['category'=> "Category 1"], 
   ['category'=> "Category 2"], 
   ['category'=> "Category 3"]

];

解决方案1:返回布尔值true / false

in_array("Category 23", array_column($catArr, 'category')); //true/false

解决方案2:返回元素索引

if(array_search("Category 1", array_column($catArr, 'category')) > 0){
    //Found
}

解决方案3:如果多次存在,则返回项目存在的次数

if(sizeof(array_keys(array_column($catArr, 'category'), "Category 1")) > 0) {
   //Found
}