2013-04-15 106 views
0

我有一個計數器變量,用於數組中項目的ID或編號。這和要添加到數組的內容在另一個數組中佔據一個位置。這另一個陣列是一個二維數組。計數器變量不遞增

基本上我正在做的是從一個數組中獲取內容,這些數組最終將被動態創建並添加到另一個數組中。然後將該陣列放入存儲陣列中。 對於我所做的,我必須這樣做。道歉。

我在想,爲什麼我的計數器變量增量只增量一次,等於一個當我print_r它和我添加的內容是數組的一部分。

當我運行這段代碼,我應該看到的結構是:

1, 1's content 
2, 2's content 
3, 3's content 

但我所看到的是:

1, 1's content 
1, 2's content 
1, 3's content 

爲什麼不是我的計數器變量誰的值將在後面給出到$ id不增加,我怎樣才能讓它增加。 通過從一個數組中獲取數據,構造另一個數組,並將其放入另一個數組,然後遞歸添加其餘內容幾乎不得不保留。我沒有太多的自由來改變代碼。 我只是不知道爲什麼計數器變量不增加。

下面是代碼:

$counter = 0; 
$added_text = array(); 
$addMe = array("orange is the keyword of the day. Tomorrows is mop.", "I do not think you understnad how much I want it. I need it and it will happen.", "I love all sorts of music. Do I consider it a gift, I am not sure. That is all I know."); 

function thing($contents, $addMe) 
{ 
    $counter++; 
    $text = strip_tags($contents); 

    $id = $counter; 
    $content = array(
     'id'  => $id, 
     'content'  => $text 
    ); 

    print_r($content); 
    echo "<br /><br />"; 
    array_push($added_text, $content); 

     foreach($addMe as $text){ 
      if(!in_array($added_text, $text)){ 
       sleep(1); 
       thing($text, $addMe); 
      } 
     } 
} 

thing('hello i am the text 1 as in the text of the first document', $toAdd); 
+1

您最初定義爲$計數器的值超出範圍中的東西()函數 –

+0

[可變範圍(http://php.net/manual/en/language.variables。 scope.php)問題 – 2013-04-15 23:05:29

+0

添加'global $ counter;'作爲函數的第一行'thing(...)' – MatRt

回答

1

你必須保持$櫃檯範圍,每次調用件事$計數器是未初始化的時間,所以是「0」雜交,然後調用計數器++,它設置它爲1。

function thing($contents, $addMe, $counter=0) 
{ 
$counter++; 

... 


foreach($addMe as $text){ 
     if(!in_array($added_text, $text)){ 
      sleep(1); 
      thing($text, $addMe, $counter); 
     } 
    } 
+0

只是將計數器設置爲默認零的參數? '$ counter = 0' – dbf

+0

噢好吧,謝謝你的解釋。即使在函數外初始化$ counter,每次函數被調用時它都是單元化的並重新初始化? '$ counter?:0;'做什麼?我從來沒有見過這種符號。 –

+0

@dbf我可以做到這一點,但我不想有任何不必要的參數,如果我可以避免它們。 –