简体   繁体   中英

PHP- Loop through an array, and use each result as a variable in a class

So, I have a simple array called $modSites, which is just a list of urls that need to be pinged.

I loop through the array:

## Get array length ##

$modLength = count($modSites);

## For loop, until end of array is reached ##

for ( $i = 0; $i < $modLength; x++ );

But now, I want to use a php class: https://github.com/geerlingguy/Ping , to ping each of the URLS, and print the results in a table. What is the most efficient way to get the values pulled from the array stuffed into a variable that I can assign to $host in the below code snippet?... so I can print the values?

require_once('Ping/Ping.php');
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency) {
  print 'Latency is ' . $latency . ' ms';
}
else {
  print 'Host could not be reached.';
}

i would do something like this:

foreach ($modSites as $site) {
  $ping = new Ping($site);
  $latency = $ping->ping();
  if ($latency) {
    print $latency;
  } else {
    print "failed.";
  }
}

if you wanted to build an array while you move through the foreach loop then maybe use something like this:

$latencyArray[$site] = $latency;

You can create a single Ping object and just change the hosts. You can also use a foreach loop:

require_once('Ping/Ping.php');
$ping = new Ping('');
foreach ($modSites as $site) {
    $ping->setHost($site);
    $latency = $ping->ping();
    if ($latency) {
      print 'Latency is ' . $latency . ' ms';
    }
    else {
      print 'Host could not be reached.';
    }
}

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