简体   繁体   中英

How to write a if condition in php based on foreach loop inside a function?

I am a newbie here and requesting assistance in writing conditional statements based on the output of this function.

 $ID = '1234';
    
 $uc = array("example1.com", "example2.com", "example3.com");
    
 function ucQuery($ucarray, $ID){
    foreach ($ucarray as $value) {
        $host = $value;
        try{
            include('info.php');
            $response = $client->getUser(array("name" => ID))->return;
            print_r($response);
        }catch (Exception $e){
            echo "false";
        }
    }
    }
    
    ucQuery($uc, $ID);

The info.php has soapclient call to the server and returns a response. When I run this I am seeing the output printed on the page. So out of 3 servers I am expecting this to be in 1 and the rest 2 returns false. all works till here.

I am basically stuck on how to take this forward. So far example,

if the user is returned from the first example1.com server, I should run another function and say this user was returned from this particular server.

if the user is not returned from all the servers, I should print an error.

Any help here is highly appreciated. Thanks a lot.

Why not something like this:

$ID = '1234';
    
$uc = array("example1.com", "example2.com", "example3.com");

function ucQuery($ucarray, $ID){
    $user_data_array=[];
    foreach ($ucarray as $value) {
        $host = $value;
        try{
            include('info.php');
            $response = $client->getUser(array("name" => ID))->return;
            print_r($response);
            $user_data_array[$value]=$response;
        }catch (Exception $e){
            echo "false";
        }
    }
    return $user_data_array;
}
    
$user_data_array = ucQuery($uc, $ID);

if (count($user_data_array) < count($uc)) {
    // not all servers responded OK
    // do whatever you need to
    echo "User '$ID' was not returned from all servers";
}

foreach ($user_data_array as $server => $response){
    another_function($ID, $server);
    echo "User '$ID' was returned from server $server";
}

Try it online

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