【问题标题】:PHP while loopPHP while 循环
【发布时间】:2011-08-06 10:42:08
【问题描述】:

我有这个非常简单的 Wordpress 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";
(...)

怎么做? :)

谢谢!

【问题讨论】:

    标签: php arrays variables while-loop


    【解决方案1】:

    您可以轻松保存在数组中

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

    print_r($data);

    $array 将在循环迭代时将数据从索引 0 存储到元素数

    【讨论】:

    • 也许还提到了分配动态变量名称的能力,这本质上是 OP 之后的内容,而不是数组(并不是说它更有效),${$name}...
    • 这不起作用,当我在 while 循环之外执行 var_dump($array) 时,它只给了我最后一个 $data 字符串...
    • @Wordpressor:您可能在任何地方都做错了,请再次检查您的代码。
    【解决方案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 计数器。如果使用上述语法保存到数组中,则会自动生成索引。

    【讨论】:

    • 虽然这确实有效并回答了 OP 的确切问题,但我无法想象这种模式比@Shakti Singh 提出的替代解决方案更可取的用例。
    • @Schwartzie,同意,这就是为什么我包含了关于使用array 的内容。不过,它们实际上只是相同功能的不同语义。
    猜你喜欢
    • 2016-11-27
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 2012-01-02
    • 2016-08-10
    相关资源
    最近更新 更多