简体   繁体   English

如何检查 php 中是否存在键/值对?

[英]How can I check if a key/value pair exists in php?

I am getting a list of schools for each athlete.我得到了每个运动员的学校名单。 If an athlete has a status of committed: true in the object, I only want to show that school.如果一个运动员在对象中的状态为committed: true ,我只想显示那个学校。 Otherwise, I want to return all properties.否则,我想返回所有属性。

This is what my data looks like:这是我的数据的样子:

...
"offers": [
    {
        "school": "Foo School",
        "committed": true
      },
      {
        "school": "Bar School",
        "committed": false
      }
    ]
...

In the above example, I only want to show "Foo School".在上面的例子中,我只想显示“Foo School”。 But if both committed properties were false I want to show "Foo Schoo" and "Bar School".但是如果两个committed属性都是false我想显示“Foo Schoo”“Bar School”。

Here is what I have currently, but am returning both regardless.这是我目前拥有的,但无论如何都会返回。

foreach ($object['athlete']['offers'] as $offer) {
    if (isset($offer['committed']) && $offer['committed'] == 1) {
       // return single school
    } else {
       // push into array & return?
    }
}

Thank you for any suggestions!感谢您的任何建议!

I think this is what you were looking for, please correct me if I'm wrong.我想这就是你要找的,如果我错了,请纠正我。 If all of them are false, then it returns all.如果所有这些都是假的,那么它返回所有。 If one or more are true, it returns the first one that's true:如果一个或多个为真,则返回第一个为真的:

<?php

$offers = array(
    array("school" => "Foo School",
    "committed" => true
  ),
  array(
    "school" => "Bar School",
    "committed" => false
  ));

$fullReturn = "";
$flag = false;
foreach ($offers as $offer) {
    if (isset($offer['committed']) && $offer['committed']) {
       echo $offer['school'];
       $flag = true;
       break;
    } else {
       $fullReturn .= $offer['school'] . "<br />";
    }
}

if (!$flag) {
    echo $fullReturn;
}

?>

If you have two array and you want to check if the $haystack array have minimum $needle array's element and they match or not then you can use that function如果您有两个数组并且您想检查 $haystack 数组是否具有最小 $needle 数组的元素并且它们匹配与否,那么您可以使用该函数

    function array_match($needle, $haystack){
        $haystack =  (array) $haystack;
        $needle =  (array) $needle;
        foreach ($needle as $key => $value) {
            if( trim($value) != trim($haystack[$key]) ){
                return false;
            }
        }
        return true;
    }

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

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