【问题标题】:save value of foreach loop in locally intiliazed array in php将foreach循环的值保存在php中的本地初始化数组中
【发布时间】:2021-06-09 02:35:48
【问题描述】:

我想将来自查询的 foreach 循环的值保存在本地初始化的数组中。因为我不知道如何在数组中动态保存 foreach 循环的值。代码如下所示:

$result = $wpdb->get_results ( "SELECT * FROM interestclass where SortingCode='bake1r20210113' || SortingCode='bake1r20210225' || SortingCode='bake1r20210506' || SortingCode='bake1r20210612' || SortingCode='bake1r20210813'" );
$resultCount = count($result);
$arrayofDates[]=array();
foreach ( $result as $key=>$print )  

     {
         if(substr($print->LessonCode,6)=="01")
         {
             $arrayofDates[]=date("m/d", strtotime(str_replace(' ', '', $print->StartDate)));
             echo "<td>(".$arrayofDates." ,</td>";
         }
}

【问题讨论】:

    标签: php arrays foreach


    【解决方案1】:

    如果您想将日期保存到 $arrayofDates。代码如下所示

    $result = $wpdb->get_results ( "SELECT * FROM interestclass where SortingCode='bake1r20210113' || SortingCode='bake1r20210225' || SortingCode='bake1r20210506' || SortingCode='bake1r20210612' || SortingCode='bake1r20210813'" );
    $resultCount = count($result);
    $arrayofDates = []; // or $arrayofDates = array()
    foreach ( $result as $key=>$print ){
             if(substr($print->LessonCode,6)=="01")
             {
                 $date = date("m/d", strtotime(str_replace(' ', '', $print->StartDate)));
                 $arrayofDates[] = $date
                 echo "<td>".$date." ,</td>"; //you should not echo array in each loop and not concat array to str
             }
    }
    

    希望对您有所帮助。如果您还有其他问题,请在下方评论

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-30
      • 1970-01-01
      相关资源
      最近更新 更多