【问题标题】:Foreach loop inside while loop returns only one resultwhile循环内的foreach循环只返回一个结果
【发布时间】:2021-09-24 20:57:00
【问题描述】:

正如标题所说,while循环中的foreach循环只返回最后一个数组。

电流输出: 紫水晶04、彩虹07、海星14、+3金

期望的输出: 紫水晶04、彩虹07、海星14、+2小瓶、+1糖果、+3金

所以下面的代码只返回货币数组中的黄金数组。

while( $row = mysqli_fetch_assoc($show1) ) {
   // Example of $row['log_rewards'] output from the database log_rewards column:
   $row['log_rewards'] = "amethyst04, rainbow07, starfish14, vial, vial, candy, gold, gold, gold";

   // List of available currencies
   $currencyArr = "vial, candy, gold";

   $rewards = explode(', ', $row['log_rewards']);
   $curName = explode(', ', $currencyArr);

   // Declare empty strings
   $txtString = ''; 
   $curString = ''; 

   // Display cards for each reward if NOT a currency
   foreach( $rewards as $r ) {
      if( !in_array($r, $currencyNames) ) {
         $txtString .= $r.', ';
      }
   }

   // Get count of how many of each reward is present
   $values = array_count_values($rewards);

   // Display currencies that are in rewards and quantity only if exists in rewards
   // This foreach loop only shows the last currency from the $rewards array
   foreach( $curName as $cn ) {
      if( array_key_exists($cn, $values) ) {
         $curString .= ', +'.$values[$cn].' '.$cn;
      }
   }

   // Display text of rewarded cards
   $txtString = substr_replace($txtString,"",-2);

   // Print out both cards and currencies
   echo '<b>'.$row['log_title'].':</b> '.$txtString.' '.$curString;
}

我不确定这是否应该进一步解释,因为我已经提到了当前和期望的输出以及问题。 ^^;非常感谢!

【问题讨论】:

    标签: php foreach while-loop


    【解决方案1】:
    if( !in_array($r, $currencyNames) ) {
    

    因为没有名为 $currencyNames 的变量。不应该是 $curName 吗?

    【讨论】:

    • 嗨!我将$currencyNames 更改为$curName,它确实显示了其他货币!我的天啊。想扇自己耳光,我会看到我的大脑。哈哈
    猜你喜欢
    • 2014-12-05
    • 2013-10-27
    • 2016-05-22
    • 1970-01-01
    • 2013-12-18
    • 2017-03-10
    • 2014-10-26
    • 2016-03-14
    • 2011-09-26
    相关资源
    最近更新 更多