简体   繁体   English

PHP-遍历数组,并将每个结果用作类中的变量

[英]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. 因此,我有一个名为$ modSites的简单数组,它只是需要ping的URL列表。

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. 但是现在,我想使用一个php类: https : //github.com/geerlingguy/Ping ,以ping通每个URL,并将结果打印在表中。 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? 将数组中的值填充到变量中的最有效方法是什么,我可以在下面的代码片段中将其分配给$ host?...以便可以打印值?

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: 如果您想在遍历foreach循环时构建一个数组,则可以使用如下所示的内容:

$latencyArray[$site] = $latency;

You can create a single Ping object and just change the hosts. 您可以创建单个Ping对象,而只需更改主机。 You can also use a foreach loop: 您还可以使用foreach循环:

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

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

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