简体   繁体   中英

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. 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". But if both committed properties were false I want to show "Foo Schoo" and "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

    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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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