在Foreach Loop PHP中从数组读取多个值

时间:2018-07-21 20:13:50

标签: php

我想一一获取数组值并动态添加到foreach中

$tracker = array('1','2','3')

我可以通过在下面创建多个foreach来手动完成

<?php
$tracker = array( '1' );
$hashx = array( $hash );
$info = $scraper->scrape( $hashx, $tracker );
foreach ($info as $key => $value) {
    $openseed = $value['seeders'];
}

$tracker = array( '2' );
$hashx = array( $hash );
$info = $scraper->scrape( $hashx, $tracker );
foreach ($info as $key => $value) {
    $pirateseed = $value['seeders'];
}

$tracker = array( '3' );
$hashx = array( $hash );
$info = $scraper->scrape( $hashx, $tracker );
foreach ($info as $key => $value) {
    $rarbgseed = $value['seeders']; 
}
?>

但是我想一次将所有数组值动态添加到foreach中,而不是手动一个个地创建

<?php
$tracker = array('1','2','3');

$hashx = array( $hash );
$info = $scraper->scrape( $hashx, $tracker );
foreach ($info as $key => $value) {
    $openseed = $value['seeders'];
}
?>

上面的代码只读取第一个数组值,我想读取所有数组值并分别存储结果,然后像下面这样使用array_sum()计算生成的结果总数

$totalseed = array($pirateseed,$openseed,$rarbgseed);
echo 'Total <font color="green">Seeders:</font> '. array_sum($totalseed). '<br />';

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

var tracker = [1,2,3];
var tracker_counts = [];

for( let i in tracker ) {
  // scrape
  tracker_counts[i] = parseInt(Math.random() * 10); // put your $value['seeders'] here
}

console.log( "Tracker seeders individually: " + tracker_counts.join(',') );
console.log( "Seeders in total: " + tracker_counts.reduce((c,v) => c+=v ) ); // use array_sum in php

作为PHP

<?php
$tracker = [1,2,3];
$tracker_counts = [];

foreach( $tracker as $k => $v ) {
  // scrape of $v
  $tracker_counts[$k] = rand(1,9); // put your $value['seeders'] here
}

echo "Tracker seeders individually: " . implode( ', ', $tracker_counts);
echo "\n";
echo "Seeders in total: " . array_sum( $tracker_counts );

输出

Tracker seeders individually: 7, 9, 6
Seeders in total: 22

答案 1 :(得分:0)

我已经在Andreas和Pilan的帮助下弄清楚了,因此,如果有人在寻找它,我将发布最终的解决方案

<?php
$ftracker = array('udp://tracker.torrent.eu.org:451/announce', 'http://tracker.tfile.co:80/announce', 'http://retracker.spb.ru:80/announce', 'udp://open.demonii.si:1337/announce');
$hashx = array( $hash );
$info = $scraper->scrape( $hashx, $ftracker );

$openseed = [];
foreach($ftracker as $track){
    $hashx = array( $hash );
    $info = $scraper->scrape( $hashx, $track );
    foreach ($info as $key => $value) {
        $openseed[] = $value['seeders'];
    }
}
echo 'Seed for Each Tracker Separately'.implode( ', ', $openseed);
echo 'Total Seed for All Trackers'. array_sum( $openseed );
?>

感谢Andreas和Pilan