无法在php foreach语句之外设置变量

时间:2014-12-07 16:45:57

标签: php arrays variables foreach

我试图让$leadsource在foreach语句之外打印或回显,但它不起作用。

如果我在foreach语句中回显$leadsource,就像www.test.com?id=2462一样,但是如果我尝试在foreach语句之外回显$ leadsource,这就是我需要发生的事情,它会返回数组中的值错误。这让我疯了,任何人都可以给我任何帮助我会很感激。

$sourcetracking=$_GET['id'];

$LegacyIDLookupArray = array(
    '2612' => 'ADV-ShowProg',
    '2462' => 'ADV-ShowProg-3.5x7',
    '2422' => 'ADV-Mag-book'
    );


if (!empty($sourcetracking))
{
    foreach ($LegacyIDLookupArray as $LegacyID => $Oldleadsource)
    {
        if ($sourcetracking == $LegacyID)
        { 
            $leadsource = &$Oldleadsource;
            // echo "$leadsource\n"; Echoing $leadsource here works properly.             
        }        
    }
}
else
{
    echo "fail";
}

echo "$leadsource\n"; // echoing $leadsource here echo's the wrong one in the array.

2 个答案:

答案 0 :(得分:2)

试着休息一下。

// As a side note: you can check at the very beginning to see that
// the ID isn't being compromised by something by checking if 
// is_numeric. Also, you can save your 'fail' message until the very
// end when checking that your $leadsource isset. These extra points
// are not essential, but they will throw a fail at all points of the 
// code (if that is valuable at all to you)

$sourcetracking = (isset($_GET['id']) && is_numeric($_GET['id']))? $_GET['id']:false;

if($sourcetracking !== false) {
    $LegacyIDLookupArray = array(
        '2612' => 'ADV-ShowProg',
        '2462' => 'ADV-ShowProg-3.5x7',
        '2422' => 'ADV-Mag-book'
        );

         foreach ($LegacyIDLookupArray as $LegacyID => $Oldleadsource) { 
              if($sourcetracking == $LegacyID) { 
                   $leadsource = &$Oldleadsource;

                   // This is where the break goes to stop your loop
                   // when condition is met
                   break;            
               }
          }
    }

// Your $leadsource OR fail is echoed here.
echo (isset($leadsource))? $leadsource : "fail";

答案 1 :(得分:0)

original code:
$sourcetracking=$_GET['id'];

$LegacyIDLookupArray = array(
    '2612' => 'ADV-ShowProg',
    '2462' => 'ADV-ShowProg-3.5x7',
    '2422' => 'ADV-Mag-book'
    );


if (!empty($sourcetracking)) {  
            foreach ($LegacyIDLookupArray as $LegacyID => $leadsource) { 
                    if($sourcetracking == $LegacyID) { 
                        $leadsource = $_POST['LeadSource'];
                        break;            
                    }
                }
}else {
    echo"fail";
}

// You may want to do a check to make sure it is set or you will
// get a variable not found error. Even if you think it should be
// set 100% of the time, you just never know. May as well put the 
// isset in.
if(isset($leadsource)) {
   echo $leadsource;
    }