2014-05-29 15:43
浏览 72

循环遍历数组并为每个元素打印HTML dinamcly

I am trying to loop through my array which contains objects and print out the data I need into my HTML. This HTML needs to print my first element and afterwards "create" a new HTML showing my second element and so on...

This is my PHP function where I query the DB:

public function getCuponesUser(){
    $db = JFactory::getDbo();
    $user = JFactory::getUser()->id;
    $query = 'SELECT * FROM #__cuphoneo_subscripcion as cs LEFT JOIN #__k2_items as k2i ON = cs.item_id WHERE cs.user_id='.$user.' GROUP BY cs.item_id';
    $resultado = $db->loadObjectList();

    return $resultado;

This is what $resultado returns:

And this is my HTML/PHP code where I am trying to print the data retrieved:

<div class="panel-group" id="accordion">
    <div class="panel panel-info">
    $model = $this->getModel();
    $cuponesUsuario[] = $model->getCuponesUser();

    foreach($cuponesUsuario as $valor){

 <div class="panel-heading" data-toggle="collapse" data-parent="#accordion" data-target="#collapse1">
    <div class="panel-heading-left">
        <h4 class="panel-title accordion-toggle">
            Data 1
     <div class="panel-heading-right">
        <h4 class="panel-title">
            Data 2
<div id="collapse1" class="panel-collapse collapse">
  <div class="panel-body">
    <div class="panel-left">
        <div class="panel-image">
            Data 3
        <div class="panel-fecha">
            <span class="label label-info">Data 4</span>

    <div class="panel-right">
        <div class="panel-desc">
        Data 5
        <div class="panel-boton-canjear">
            <input class="btn" type="button" value="Canjear"/>
    <?php } ?>

Where it says Data 1, Data 2, Data 3...etc, is where I need to print out the different values the Query may return.

EDIT: Im pretty sure I also have to use a for but not very sure how to do this :P

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dounue1965 2014-05-29 15:51

    If $resultado already represents the array you want to loop over, then this is wrong:

    $cuponesUsuario[] = $model->getCuponesUser();

    Just do this:

    $cuponesUsuario = $model->getCuponesUser();

    Inside your foreach loop, you can access the data like this:

    <?php echo $valor->title; ?> 
    点赞 打赏 评论
  • dongtu7567 2014-05-29 15:55

    The problem is in your use of this syntax:

    $cuponesUsuario[] = //...

    The $var[]= syntax appends an object to the array $var. Because of this, $cuponesUsario is an array with one element, and that one element is your actual data structure. When you call foreach() on the array, it only executes one time because there is only one element in the array.

    Instead, remove the [] and just assign your result to $cuponesUsario directly, since it is already array data.

    点赞 打赏 评论

相关推荐 更多相似问题