0

我有一个计数器变量,用于数组中项目的 id 或编号。那和要添加到数组中的内容在另一个数组中占据一个位置。因此,该另一个阵列是二维阵列。

基本上我正在做的是从一个数组中获取内容,最终将动态创建并添加到另一个数组中。然后将该阵列放入存储阵列中。对于我正在做的事情,我必须这样做。道歉。

我想知道为什么我的计数器变量只增加一次,因为当我 print_r 它的数组和我添加的内容是其中的一部分时,它等于 1。

当我运行这段代码时,我应该看到的结构是:

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);
4

1 回答 1

1

您必须将 $counter 保持在范围内,每次调用 $counter 时都未初始化,“0”也是如此,然后您调用 counter++,将其设置为 1。

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

...


foreach($addMe as $text){
        if(!in_array($added_text, $text)){
            sleep( 1 );
            thing($text, $addMe, $counter);
        }
    }
于 2013-04-15T23:08:25.743 回答