[英]Loop through an array and use the result of each loop as a variable for inserting to MySQL
[英]PHP- Loop through an array, and use each result as a variable in a class
因此,我有一個名為$ modSites的簡單數組,它只是需要ping的URL列表。
我遍歷數組:
## Get array length ##
$modLength = count($modSites);
## For loop, until end of array is reached ##
for ( $i = 0; $i < $modLength; x++ );
但是現在,我想使用一個php類: https : //github.com/geerlingguy/Ping ,以ping通每個URL,並將結果打印在表中。 將數組中的值填充到變量中的最有效方法是什么,我可以在下面的代碼片段中將其分配給$ 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.';
}
我會做這樣的事情:
foreach ($modSites as $site) {
$ping = new Ping($site);
$latency = $ping->ping();
if ($latency) {
print $latency;
} else {
print "failed.";
}
}
如果您想在遍歷foreach循環時構建一個數組,則可以使用如下所示的內容:
$latencyArray[$site] = $latency;
您可以創建單個Ping對象,而只需更改主機。 您還可以使用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.