Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/248.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在php中将for循环结果存储为变量_Php_Variables_For Loop - Fatal编程技术网

在php中将for循环结果存储为变量

在php中将for循环结果存储为变量,php,variables,for-loop,Php,Variables,For Loop,我有这个 <?php $articlesCount = count($articles); for ($i = 0; $i < $articlesCount; $i++) { //would like to store result as a variable for use later } ?> 我希望将for循环的结果存储在一个变量中,以便以后可以使用该变量从循环中调用所需的信息。此时,我无法理解语法。任何建议都将

我有这个

    <?php
    $articlesCount = count($articles);

    for ($i = 0; $i < $articlesCount; $i++) {
      //would like to store result as a variable for use later
    }
    ?>


我希望将for循环的结果存储在一个变量中,以便以后可以使用该变量从循环中调用所需的信息。此时,我无法理解语法。任何建议都将不胜感激。

您将要保存的内容放入一个数组中。随着
$i
大小的增加,所有数据将放在不同的索引中

<?php
$articlesCount = count($articles);
$result = []; // Empty array

for ($i = 0; $i < $articlesCount; $i++) {
  $result[$i] = $variable; // Variable = whatever you want to save
}
?>

我不知道您是要为每次迭代保存一个结果,还是只保存一个全局结果

如果要保存每次迭代的结果,可以使用数组。 例如,这将生成值为0,2,4,6的数组

<?php
$articlesCount = count($articles);
$result = array();

for ($i = 0; $i < $articlesCount; $i++) {
  $result[$i] = $i * 2;
}
echo $result[2]; //will show "4" because the it is the 3rd element in the array (we start counting at 0, not 1)
?>

如果要保存全局结果,例如数组中所有元素的总和,请执行以下操作:

<?php
$articlesCount = count($articles);
$result = 0;

for ($i = 0; $i < $articlesCount; $i++) {
  $result = $result + $i ;
}
?>


您已经在
$articles
变量中找到了它。为什么需要将其重新分配给另一个变量?您可以通过提供键来访问阵列信息,例如
$articles[1]
。如果它是一个对象数组,您可以通过
$articles[1]->name

访问数据,因为for循环中没有任何内容。也许其中的一些示例代码会对解决方案有所帮助。我们不知道你想做什么。可能的解决方案是输出缓冲或字符串的简单连接。ty这是我所需要的,非常感谢。