views:

139

answers:

3
function sitemap_galerija($tablica)
{
    require("include/konekcija.php");

    if($tablica == 'kategorije')
    {
     // Connect do database

        ...

     while($row = mysql_fetch_array($sql_result))
     {
      $kategorija['naziv'][] = $row["naziv"];
      $kategorija['naziv_url'][] = $row["naziv_url"];
     }

     return $kategorija;
    } 
}

I managed to print values of array but can't figure out how to handle with array keys. I would like the print to be like this:

$kategorije = sitemap_galerija('kategorije');

foreach($kategorije as $kat)
{  
    echo  "<li><a href='$kategorija[naziv_url]'>$kategorija[naziv]</a></li>";
}

Ile

+2  A: 

You will need the key to iterate both arrays in parallel:

for ($i=0, $n=count($kategorije['naziv_url']); $i<$n; ++$i) {
    echo  "<li><a href='".$kategorija['naziv_url'][$i]."'>".$kategorija['naziv'][$i]."</a></li>";
}
Gumbo
thanks for answer, I think I'll satisfy with Joost's solution.
ile
+2  A: 

You want your $kategorija array to use normal numbers as keys, and for each number you'd have an array wit the naziv and naziv_url keys:

while($row = mysql_fetch_array($sql_result))
{
    // $kategorija['naziv'][] = $row["naziv"];
    // $kategorija['naziv_url'][] = $row["naziv_url"];
    $kategorija[] = array('naziv' => $row['naziv'], 'naziv_url' => $row['naziv_url']);
    // The following works as well, but then you store all the keys in the kategorija array and I don't know if that's what you want:
    // $kategorija[] = $row;
}

Then you can adjust your foreach loop to be something like:

foreach($kategorije as $kat)
{  
    echo  '<li><a href="' . $kat['naziv_url'] . '">' . $kat['naziv'] . '</a></li>';
}
JoostK
Thanks, this is just what I needed!
ile
+3  A: 

You really have to save relation between naziv and naziv_url, it'll help you in the future. Just get it from DB like this:

$kategorija[$row['naziv_url']] = $row["naziv"];

and then you can enumerate this array like this:

foreach($kategorija as $naziv_url => $naziv) {
}

Always use the value that you know is unique as keys, I supposed url in unique in this case.

vava
This is great solution for this example of mine. But if I need to get more data from DB (id, date, etc.) than this is not good solution. But for just 2 variables this is really nice ;)Thanks,Ile
ile
You always can use sub arrays :) Like in `$collection[$row['id']] = array('name' => $row['name'], 'value' => $row['value'])`. Or even better, as I always do lately, `$collection[$row['id']] = $row`.
vava
Or multiple different sets of key->value if it makes more sense.
vava
hmm, this $collection[$row['id']] = $row seems interesting :)
ile