简体   繁体   English

如何确定任何数组键的值是否是我要寻找的值?

[英]How can I tell if the value of any array key is the value I'm looking for?

I have an array of arrays like this: 我有一个这样的数组数组:

$cart = Array ( 
[0] => Array ( [TypeFlag] => S [qty] => 2 [denom] => 50  [totalPrice] =>  100 )
[1] => Array ( [TypeFlag] => V [qty] => 1 [denom] => 25  [totalPrice] => 25 ) 
[2] => Array ( [TypeFlag] => C [qty] => 1 [denom] => 25  [totalPrice] => 25 ) 
) 

Is there any way, short of looping through all of them and checking one at a time, to determine if the TypeFlag value for any of them is S? 是否有什么方法可以循环遍历所有对象并一次检查一个,从而确定其中任何一个的TypeFlag值是否为S?

Try this: 尝试这个:

foreach($cart as $key => $value) {
    if ($value['TypeFlag'] == 'S') {
        return $key;
    }
}

This would return the key of the sub-array that has a TypeFlag value of S . 这将返回TypeFlag值为S的子数组的键。 However, this would stop after it finds the first sub-array that matches your search pattern. 但是,这将在找到与您的搜索模式匹配的第一个子数组后停止。 Not sure what your desired output is tho and how many results are expected. 不确定所需的输出是什么以及预期的结果是多少。 If you can provide more info, I can give you a more accurate example. 如果您可以提供更多信息,我可以给您一个更准确的例子。

Given a function that returns the TypeFlag for each element of your array: 给定一个为数组的每个元素返回TypeFlag的函数:

function get_type_flag($item) {
    return $item["TypeFlag"];
}

You could apply that function to each element in the array: 您可以将该函数应用于数组中的每个元素:

$typeflags = array_map("get_type_flag", $cart);

and see if S is in that array: 并查看S是否在该数组中:

if (in_array("S", $typeflags)) {
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM