How to sort alternative keys and values from an associative array in PHP

oceanwap

New Member
Messages
24
Reaction score
0
Points
0
I have an array in which I stores key and values using post method, so let's assume it looks like this
PHP:
$links = array("PHP" => "http://",
"Zend" => "http://zend.com","Mysql" => "http://mysql.com",
"Ubuntu" => "http://ubuntu.com");
Now for fetching values I can do this
PHP:
foreach($links as $title => $link) {
echo "<tr><td><a href=\"$link\">$title</a></td></tr>"; 
}
So I get the following html
HTML:
<tr><td><a href="http://php.net">PHP</a></td></tr>
<tr><td><a href="http://zend.com">Zend</a></td></tr>
<tr><td><a href="http://dev.mysql.com">Mysql</a></td></tr>
<tr><td><a href="http://ubuntu.com">Ubuntu</a></td></tr>
But I want output like this, so document looks fancy
HTML:
<tr><td class="songbg"><a href="http://php.net">PHP</a></td></tr>
<tr><td><a href="http://zend.com">Zend</a></td></tr>
<tr><td class="songbg"><a href="http://dev.mysql.com">Mysql</a></td></tr>
<tr><td><a href="http://ubuntu.com">Ubuntu</a></td></tr>
How I can achieve this?
 

dlukin

New Member
Messages
427
Reaction score
25
Points
0
Code:
$counter = 0 ;
$tdclass = ''

foreach($links as $title => $link) {

$counter++ ;
$tdclass = ($counter % 2 == 0 ) ? ' class="songbg" ' : '' ;

echo "<tr><td$tdclass><a href=\"$link\">$title</a></td></tr>"; 

}

should work.
 
Last edited:

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
Slightly simpler, toggle the value in a variable.
PHP:
<?php $parity=0; ?>
<ul>
    <?php foreach ($links as $title => $link) { ?>
        <li><a href="<?php echo $link ?>" class="<?php echo $parity ? 'odd' : 'even' ?>"><?php echo $title?></a></li>
        <?php
        $parity = !$parity; 
    } 
    ?>
</ul>

Note that I've also switch from a table to a list, since that's what the data is, structurally speaking. Don't abuse tables.
 
Top