【问题标题】:PHP show values of associative array when one of the values equals a specified value当其中一个值等于指定值时,PHP 显示关联数组的值
【发布时间】:2010-10-07 16:58:49
【问题描述】:

我有一个 Mysql 记录集,我已将它放入关联数组中,以便我可以反复重用它。

我使用这个函数将值放入数组中:

while(($Comments[] = mysql_fetch_assoc($rsComments)) || array_pop($Comments));

这是 print_r($Comments) 显示的内容

Array ( [0] => Array ( [CommentID] => 10 [Comment] => Ouch [CommentAuthor] => Randy Krohn [CommentDate] => 2010-10-06 17:19:49 [ID] => 1231 [CategoryID] => 42 ) [1] => Array ( [CommentID] => 12 [Comment] => This is the Dirty Duck [CommentAuthor] => John Lemoine [CommentDate] => 2010-10-06 17:22:43 [ID] => 1411 [CategoryID] => 42 ) [2] => Array ( [CommentID] => 13 [Comment] => Talk about deja vu! [CommentAuthor] => dber [CommentDate] => 2010-10-06 17:24:48 [ID] => 1473 [CategoryID] => 42 ) )

我正在循环浏览图像列表,并且我只想显示与指定 ImageID(例如 1473)的图像关联的 cmets。

我只需要显示ID等于指定值的那些吗?

这一定很容易,但由于某种原因,它只是在我头上飞过。

感谢您的帮助!

【问题讨论】:

    标签: php mysql associative-array


    【解决方案1】:

    最简单的方法是使用foreach 循环遍历'Comments' 关联数组(又名字典)并检查'ID' 键的值,如果它与所需的值匹配,则打印'Comment' 键的值:

    $imageId = 1473;
    foreach($Comments as $comment) {
        if($comment['ID'] == $imageId) {
            echo $comment['Comment'];
        }
    }
    

    【讨论】:

    • 非常感谢。我知道这很简单,今天早上我就是无法理解。正是我想要的。
    • 为什么这个函数不包含记录集中的第一个值?while(($Comments[] = mysql_fetch_assoc($rsComments)) || array_pop($Comments));
    • 应该包含第一条记录,除非您调用了 mysql_fetch_assoc 或任何其他 fetch 方法,这些方法会在此之前但在调用查询之后将结果集指针向前移动。
    猜你喜欢
    • 1970-01-01
    • 2010-10-22
    • 2012-02-08
    • 1970-01-01
    • 2021-06-14
    • 2017-01-10
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多