开发者

PHP while loop

开发者 https://www.devze.com 2023-02-25 07:31 出处:网络
I have this very simple Wordpress while loop: $loop = new WP_Query( arg开发者_如何学Cs ) ); while ( $loop->have_posts() ) : $loop->the_post();

I have this very simple Wordpress while loop:

$loop = new WP_Query( arg开发者_如何学Cs ) );

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

This gives me something like:

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

I want to save these values from while loop as an array or variables, eg.

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

How to? :)

Thanks!


You can save in array easily

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

    endwhile; 

print_r($data);

$array will store data from index 0 to the number of elements while loop iterate


Use a counter $i to keep track of the number, and then you can save the results either as an array or as a set of variables.

$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; 

You only need to use the $i counter if you use the second method. If you save into an array with the above syntax, the indexes will be generated automatically.

0

精彩评论

暂无评论...
验证码 换一张
取 消