Print PHP array data

Asked

Viewed 271 times

2

I am trying to print the data I have in the array. It works, I can see the data. My problem is that I want to print these various data inside the same div. As I have so prints only one value. And I won’t put the div in the foreach Otherwise you’ll do another div.

foreach($array_resultados as $key =>$value){
                    //echo "<label><b>".$value['title']."</b></label><br>";
                }
                echo 
                    "<td class='cal_today'><b>

                        <div class =divtoday>
                            <br>".$value['title'] ."
                        </div>
                    </td>"; 
  • 1

    You closed the foreach before printing the values. And there is a spare key.

2 answers

5

The most practical way is to store the HTML the cycle is generating in a variable and after that make use of the variable where desired:

// iniciar variável a vazio
$htmlDoForEach = '';

// por cada entrada na matriz
foreach ($array_resultados as $key => $value) {

    // gerar HTML e adicionar à variável
    $htmlDoForEach.= '
    <div class="divtoday">
        <br>'.$value["title"].'
    </div>';
}

// usar o HTML
echo '<div id="minhaGrandeDiv">'.$htmlDoForEach.'</div>';

Note: In the code of your question there are some incorrect things with the Markup HTML and with the } in PHP that seem to be closing the cycle of foreach before actually making use of the values in the matrix.

  • It doesn’t get more efficient to do echo HTML every iteration of foreach?

  • I don’t think so, I also do so!

  • 1

    @Jorgeb. Personally I do: Collect data; Prepare data; Use data. It is the practical model that I have been using for many years and has proved to be the most flexible. But in terms of efficiency, I think it "does not heat or cool" in a scenario like the one on this topic.

0


You can make the following code:

$titles = "";
foreach($array_resultados as $key =>$value){
  $titles .= "<label><b>".$value['title']."</b></label><br>";
}
echo  "<td class='cal_today'><b>
          <div class =divtoday>".$titles."</div>
      </td>"; 

  • 1

    Hi, Daniel, welcome to [en.so]. It’s nice to explain, albeit briefly, why your code solves the problem presented. Check out.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.