Я пытаюсь получить $leadsource
для печати или эха вне инструкции foreach, но он не работает.
Если я эхо $leadsource
внутри инструкции foreach, например, так: www.test.com?id=2462
он работает, но если я пытаюсь эхо $ sourceource за пределами инструкции foreach, то это то, что мне нужно, оно возвращает неправильное значение в массиве. Это сводит меня с ума, любая помощь, которую кто-либо может мне дать, я буду признателен.
$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 the wrong one in the array.
Попробуйте вставить паузу.
// 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";
&
...
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;
}