【问题标题】:Looping though data multiple times from array从数组中多次循环数据
【发布时间】:2020-11-14 20:58:39
【问题描述】:

如果数据多次存储在数组中,我希望循环多次。

我将视频 ID 作为数组存储在数据库中,然后使用以下代码调用此数据;

$lessonSingleResultsql = "
SELECT * 
  FROM `video` 
 WHERE `id` IN ('".$lessonsResultDataDecode."') 
 ORDER 
    BY field(id,'".$lessonsResultDataDecode."');";

$lessonSingleResult = $db->prepare($lessonSingleResultsql);
if ($lessonSingleResult->execute()) {
while ($row = $lessonSingleResult->fetch(PDO::FETCH_ASSOC)) {
  echo $row['title'];
}
}

$lessonResultDataDecode 的值

 1','5','7','11','12','1','1','4','4','4','4','4','4','2','2','1','4','1','1','1','1','1','9','6','1

$lessonsResultData 的值

 Array
 (
     [videos] => [1,5,7,11,12,1,1,4,4,4,4,4,4,2,2,1,4,1,1,1,1,1,9,6,1]
 )

然后它将为每个视频回显一次标题,但如果该值被存储多次,我想再次回显。

例如标题为 1、标题为 5、标题为 7、标题为 11、标题为 12、标题为 1、标题为 1,等等...

【问题讨论】:

  • 顺便说一句,您没有正确准备查询。

标签: php mysql arrays pdo while-loop


【解决方案1】:

我不确定这是否会对您有所帮助,因为您要求的结果有点混乱,但是如果您想遍历作为查询结果收到的数组,您可以执行以下操作:

    #as i don't know your table schema i'll assume that title have an array called videos
    while ($row = $lessonSingleResult->fetch(PDO::FETCH_ASSOC)) {
        $allTitles[] = $row['title']['videos'];
    }
    #iterate all the titles received from query
    foreach($allTitles as $titles){
        #iterates through each key inside of each title
        foreach($titles as $title){
            echo "Title for {$title}".PHP_EOL;
        }
    }

更多信息:https://www.php.net/manual/en/control-structures.foreach.php

【讨论】:

    猜你喜欢
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    相关资源
    最近更新 更多