开发者

PHP foreach inside variable

开发者 https://www.devze.com 2023-02-26 19:27 出处:网络
How would I include a foreach function inside a variable. The code should explain what I mean. $list = get_posts(\'post_type=services&numberposts=-1\');

How would I include a foreach function inside a variable. The code should explain what I mean.

$list = get_posts('post_type=services&numberposts=-1');
    foreach ($list as $post) :
        $title = $post->post_title; 


    $return = '<li>
                    <a href="#main_content_inner" onClick="slide(this); return false" rel="catalogue_sevices_page">'.$title.'</a>
                </li>';
                endforeach;

That is not quite correct. I am trying to make it so that $return displays all the posts from the type services in the format

  • So effectively I am after::

    $list = get_posts('post_type=services&numberposts=-1');
        foreach ($list as $post) :
            $title = $post->post_title; 
    

    And therefore the output from $return should look something like this

    <li><a href="#content1" onClick="slide(this); return false" rel="catalogue_sevices_page">Title 1</a></li>
    <li><a href="#content2" onClick="slide(this); return false" rel="catalogue_sevices_page">Title 2</a><开发者_如何学Python/li>
    <li><a href="#content3" onClick="slide(this); return false" rel="catalogue_sevices_page">Title 3</a></li>
    

    Any ideas,


    you have to use concatenation to store data in a variable with in foreach loop

     $return .= '<li>....
    

    and then return the $return variable before foreach end

     return $return;
    endforeach;
    


    Simply append with the .= operator.

    $return = '';
    $list = get_posts('post_type=services&numberposts=-1');
    foreach ($list as $post) {
        $title = $post->post_title; 
        $return .= '<li>
                    <a href="#main_content_inner" onClick="slide(this); return false" rel="catalogue_sevices_page">'.$title.'</a>
                </li>';
    }
    return $return;
    
  • 0

    精彩评论

    暂无评论...
    验证码 换一张
    取 消