2011-04-15 162 views
2

我有一個非常簡單的WordPress while循環:PHP while循環

$loop = new WP_Query(args)); 

while ($loop->have_posts()) : $loop->the_post(); 
    $data = grab_something(args); 
    echo $data; 
    echo "<br/"; 
endwhile; 

這給了我這樣的:

datastring1 
datastring2 
anotherdata 
somethingelse 
and else 
and so forth 
(...) 

我想從while循環這些設置保存爲一個數組或變量,例如。

$data1 = "datastring1"; 
$data2 = "datastring2"; 
$data3 = "anotherdata"; 
(...) 

如何? :)

謝謝!

回答

2

使用計數器$i元素的數量來跟蹤的數字,然後您可以將結果保存爲數組或一組變量。

$loop = new WP_Query(args)); 

$i = 0; 
while ($loop->have_posts()) : $loop->the_post(); 
    $data = grab_something(args); 
    $i++; 
    $array[] = $data; // Saves into an array. 
    ${"data".$i} = $data; // Saves into variables. 
endwhile; 

您只需要如果使用第二種方法使用$i計數器。如果使用上面的語法保存到數組中,索引將自動生成。

3

可以在陣列節省容易

$array=array(); 
    while ($loop->have_posts()) : $loop->the_post(); 
     $data = grab_something(args); 
     $array[]=$data; 

    endwhile; 

print_r($data);

$array將從索引0數據存儲到while循環迭代

+0

也許還會提及賦予動態變量名稱的能力,這個名稱本質上是OP之後的,而不是數組(不是它更有效),用'$ {$ name}`...... – 2011-04-15 15:32:43

+1

這不是工作,當我在while循環之外做var_dump($ array)時,它只給出我最後一個$ data字符串... – Wordpressor 2011-04-15 15:39:09