Martin AJ Martin AJ - 4 months ago 10
PHP Question

How can I make a dynamic loop?

I have this PHP array:

echo "<pre>";
print_r($notifications);

/* output:

Array
(
[0] => Array
(
[score] => 120
[type] => 5
[post_id] => 1
[subject] => a subject
[range_day] => today
)

[1] => Array
(
[score] => 6
[type] => 4
[post_id] => 2
[subject] => a subject
[range_day] => today
)

[2] => Array
(
[score] => 2
[type] => 4
[post_id] => 3
[subject] => a subject
[range_day] => yesterday
)
)
*/


And this is expected output:

<ul>
<li>
<p class="subject">a subject<span> | type:5</span></p>
<div class="score">Your score: 120</div>
<a href="/1/a-subject">
<span class="date">today</span>
</li>
<li>
<p class="subject">a subject<span> | type:4</span></p>
<div class="score">Your score: 6</div>
<a href="/2/a-subject">
<span class="date">today</span>
</li>
<li>
<p class="subject">a subject<span> | type:4</span></p>
<div class="score">Your score: 2</div>
<a href="/3/a-subject">
<span class="date">yesterday</span>
</li>
</ul>


Also here is my current code:

$html = "<ul>";
foreach ( $notification as $item1 ) {

$html .= "<li>";
foreach ( $item as $item2 ) {

// in here I need to put different tags for different $item2. How?
}
$html .= "</li>";

}
$html = "</ul>";


As you see, I need to use multiple different tags for each key .. How can I manage that? I mean I need to surround first key into
<div>
tag, second key into
<span>
tag and etc .. How can I do that?

Answer

My preferred approach is to separate the PHP logic from the HTML as much as possible. It makes for much simpler html:

$template = <<< 'TXT'
<li>
   <p class="subject">{{subject}}<span> | type:{{type}}</span></p>
   <div class="score">Your score: {{score}}</div>
   <a href="/{{post_id}}/{{no_space_subject}}"> 
   <span class="date">{{range_day}}</span>
</li>
TXT;
$links = '';

foreach ($notifications as $n){
    $n['no_space_subject'] = str_replace(' ','-',$n['subject']);
    //replace {{VALUE}} with $n[VALUE] in the template
    $links .= preg_replace_callback('/{{([^}]+)}}/',
            function($m) use ($n){return $n[$m[1]];},
            $template
        );
}

Then later in your html, you can just output the results:

<ul><?=$links?></ul>

Live demo