【问题标题】:php: loop through a list of numbersphp:循环遍历数字列表
【发布时间】:2012-12-30 19:07:15
【问题描述】:

我有一个这样的数组:

Array (
[0] => stdClass Object ( [ID] => 1 [user_id] => 1 [post_id] => 929,924,875,839,850,720,642,1109,917,935,911,1174,1173,1172,903,892,1189,865,1386 ) 
[1] => stdClass Object ( [ID] => 2 [user_id] => 75 [post_id] => 903,704,477,9,455 ) 
[2] => stdClass Object ( [ID] => 3 [user_id] => 78 [post_id] => 917,911 ) 
[3] => stdClass Object ( [ID] => 4 [user_id] => 80 [post_id] => 903,1109,642 )
)

我写了一个 foreach 循环来遍历每个元素:

$apples = $wpdb->get_results("SELECT ID, user_id, post_id FROM table_name" );

foreach ( $apples as $apple ) 
    {
        $user_info = get_userdata($apple->user_id);
        $post_title = get_the_title($apple->post_id);

        echo '<ul><li>' . $user_info->user_login . '</li>';
        echo '<li>' . $post_title . '</li>';
        echo '</ul>';
    }

如何循环遍历在[post_id] 中找到的每个 ID?现在它只显示[post_id] 中第一个数字的标题。不过,我需要它遍历它们中的每一个。有什么想法吗?

【问题讨论】:

  • 你能把get_userdata asnd get_the_title 的代码贴出来吗?

标签: php wordpress foreach


【解决方案1】:

类似:

<?php
...
foreach( explode( ',', $apple->post_id ) as $post_id ) {
// Do your stuff
}

会的

【讨论】:

  • 工作就像一个魅力!谢谢!
【解决方案2】:

你可以试试

foreach ( $apples as $apple ) {
    $user_info = get_userdata($apple->user_id);
    echo '<h4>' . $user_info->user_login . '<h4>';
    echo "<ul>";
    foreach ( explode(",", $apple->post_id) as $postID ) {
        printf('<li>%s</li>', get_the_title($postID));
    }
    echo '</ul>';
}

【讨论】:

    猜你喜欢
    • 2016-05-03
    • 2013-06-22
    • 2014-09-19
    • 2012-01-19
    • 1970-01-01
    • 2011-05-23
    • 2012-11-14
    相关资源
    最近更新 更多