简体   繁体   中英

How do I simplify PHP code that can run 1 or 5 or 100 times?

I have a PHP code that can run a number of times depending on a variable that I set like this:

$pages = '2';

The rest of the code is like this (up to 10 actually, but I just wrote the first 3 of each here):

// STEP 1
unlink('merge1.json');
unlink('merge2.json');
unlink('merge3.json');

// STEP 2
$url_one = 'https://xxx.yyy.zzz/?offset=0';
$url_two = 'https://xxx.yyy.zzz/?offset=100';
$url_three = 'https://xxx.yyy.zzz/?offset=200';

// STEP 3
if ($pages >= '1'){
$grab_one = grab_file($url_one,'/home/dir/merge1.json');
}
if ($pages >= '2'){
$grab_two = grab_file($url_two,'/home/dir/merge2.json');
}
if ($pages >= '3'){
$grab_three = grab_file($url_three,'/home/dir/merge3.json');
}

// STEP 4
$one = json_decode(file_get_contents('merge1.json'));
$two = json_decode(file_get_contents('merge2.json'));
$three = json_decode(file_get_contents('merge3.json'));

// STEP 5
if ($pages == '1'){
    $merge = (array)$one->results;
}
if ($pages == '2'){
    $merge = array_interlace((array)$one->results,(array)$two->results);
}
if ($pages == '3'){
    $merge = array_interlace((array)$one->results,(array)$two->results,(array)$three->results);
}

In this case, it would run 2 times.

This has worked fine for me as long as I had to do it for like 5 or even 10 pages, but now I might have to run it for 50 or 100 pages and it seems overkill having to write the code again for each page, possibly having to write the code 100 times once for each page.

Is there any easy way I can achieve this?

It's easy with a for loop:

for ($i = 1; $i <= $pages;$i++){
// your code
echo $i;
};

Test it out and change it till it fits.

if $pages = 5, then it will echo:

1 2 3 4 5

it will start at 1 and end till $i = 5 is reached.

A for loop would let you run each line of code once, for each number,

In the example below, '$i' would contain the number '1', then '2' then '3' all the way up to your maximum value (50, 100, whatever)

Now this is off the top of my head, I've not tested it, but it's a starting point.

$pervious_merge;
for ($i = 1; $i<=maximum_value; $i++){
    unlink('merge'.$i.'.json');
    $url = 'https://xxx.yyy.zzz/?offset='.$i*100;
    if ($pages >= $i){
        $grab = grab_file($url,'/home/dir/merge'.$i.'.json');
    }
    $decode = json_decode(file_get_contents('merge'.$i.'.json'));
    if ($pages == $i){
        $merge = array_interlace($previous_merge, (array)$decode->results);
        $previous_merge = $merge;
    }
}

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