0

我有多个变量$soft0 , $soft1 , $soft2 , $soft3 , $soft4 , $soft5,也喜欢$fo0 , $fo1 , $fo2 , $fo3 , $fo4 , $fo5,但如果我想在这里应用一个 if 条件,那么它会显示错误。代码:

for ($i=0; $i<=29; $i++) {
    $soft$i = str_replace(" ", "+", $fo$i); // this line showing an error
    $link_f_u = $html->find('h3', 0);
    $keyy = $link_f_u->plaintext;
    if ($soft$i==$keyy){
        continue;
    } else { 
        publish($soft$i);
    }
}

修改此代码的任何想法?

4

3 回答 3

3

This will fix your error, but I would highly recommend you take a look at arrays: http://php.net/manual/en/language.types.array.php

for($i=0;$i<=29;$i++){
    $softVarName = "soft" . $i;
    $foVarName = "fo" . $i;

    $$softVarName = str_replace(" ", "+", $$foVarName);
    $link_f_u = $html->find('h3', 0);
    $keyy = $link_f_u->plaintext;
    if ($$softVarName==$keyy){
        continue;
    } else { 
        publish($$softVarName);
    }
}
于 2013-01-03T19:40:07.217 回答
2

This should fix the issue.

for($i=0;$i<=29;$i++){
    ${'soft' . $i} = str_replace(" ", "+", ${'fo' . $i}); // this line showing an error
    $link_f_u = $html->find('h3', 0);
    $keyy = $link_f_u->plaintext;
    if (${'soft' . $i} == $keyy){
        continue;
    } else { 
        publish(${'soft' . $i});
    }
}
于 2013-01-03T19:40:48.423 回答
2

Option 1 (best option):

change $soft0 ... $soft10 to arrays looking like $soft[0] .. $soft[10]. You can then use count() in your for loop:

for($i=0;$i<=count($soft);$i++){
    $soft[$i] = str_replace(" ", "+", $fo[$i]);
    $link_f_u = $html->find('h3', 0);
    $keyy = $link_f_u->plaintext;
    if ($soft[$i]==$keyy){
        continue;
    } else { 
        publish($soft[$i]);
    }
}

Option 2:

You can also use double dollar sign, however this is messy and can result in errors that are hard to catch.

$soft_name = 'soft'.$i;
$fo_name = 'fo'.$i;
$$soft_name = str_replace(" ", "+", $$fo_name);
于 2013-01-03T19:41:00.000 回答