如何在循环外存储变量

时间:2014-05-09 15:13:08

标签: php

我在循环外面的变量有问题。我想从下面显示的$programme_title循环中存储foreach $time_arr变量,然后返回一个这样的字符串列表:

Paid Programming The Mentalist - Black HeartsAnthony Bourdain Parts Unknown - Russia
NFL Live StosselBad Dog! - Bad to the BoneHouse - Son of Coma GuyCutlery Corner Wild
The Real Housewives of Atlanta - Secrets RevealedThe Real Housewives of Atlanta - Secrets Revealed
The Real Housewives of Atlanta - Secrets Revealed The Real Housewives of Atlanta - Secrets Revealed 
The Real Housewives of Atlanta - Secrets Revealed The Real Housewives of Atlanta - Secrets Revealed
The Real Housewives of Atlanta - Secrets RevealedThe Real Housewives of Atlanta - Secrets Revealed

当我使用此代码时:

 foreach($programme_arr as $programme)
  {
    $programme1 = $programme->item(0)->nodeValue;
    $programme_title = $programme1;
  }
  echo $programme_title;

或试试这个:

foreach($programme_arr as $programme)
{
  $programme1 = $programme->item(0)->nodeValue;
  $programme_title = $programme1;
}


foreach($time_arr as $time)
{
   echo $programme_title;
}

它不起作用。所以,我尝试了这段代码:

foreach($programme_arr as $programme)
{
  $programme1 = $programme->item(0)->nodeValue;
  $programme_title = $programme1;
  echo $programme_title;
}

并找回了这个庞大的字符串列表:

    Step Up 3The 700 Club The Fresh Prince of Bel-Air - Not With My Cousin You Don't
The Fresh Prince of Bel-Air - Viva Lost Wages The Fresh Prince of Bel-Air - There's the Rub
The Fresh Prince of Bel-Air - There's the RubSummer Sexy With T25!Dr. Ordon's Secret!
The 700 ClubAirbrushed BeautySleep Better!Joseph PrinceLife Today With James Robison - SMF Special 1
Joyce Meyer: Enjoying Everyday LifeShaun T's Focus T25That '70s Show - The Velvet Rope
That '70s Show - Laurie and the ProfessorThat '70s Show - HalloweenThat '70s Show - Van Stock

依旧......

您能否告诉我如何将$programme_title的变量存储在foreach $time_arr中以允许我打印上面的字符串列表?

1 个答案:

答案 0 :(得分:0)

这是变量范围的问题。如果要在循环完成时访问它,则变量必须存在于循环外部。如果你这样做:

$programme_title = NULL;
foreach($programme_arr as $programme) {
    $programme1 = $programme->item(0)->nodeValue;
    $programme_title = $programme1;
}

echo $programme_title;

您将回显$programme_arr中最后一项的标题。如果你想获得所有的标题,需要把它们放在一个数组中:

$titles = array();
foreach($programme_arr as $programme) {
    $programme1 = $programme->item(0)->nodeValue;
    $titles[] = $programme1;
}

print_r($titles);