0

My tags are showing in the inner foreach loop in the right order.

I would like to comma separate them but am not sure how.

Is there a better way to display my tags without using the second foreach loop?

$people = array();

while($row = mysqli_fetch_array($rs, MYSQLI_ASSOC)){
       if(!isset($people[$row["id"]])){
            $people[$row["id"]]["id"] = $row["id"];
            $people[$row["id"]]["tag"] = $row["tag"];
            $people[$row["id"]]["tags"] = array();
       }
     array_push($people[$row["id"]]["tags"],  array("id"=>$row["tags_id"],"tag_name"=>$row["tag"]));
}

foreach($people as $pid=>$p){

    echo "(#{$p['id']}) ";

     foreach($p["tags"] as $tid=>$t){
     echo "<a href='#'>{$t['tag_name']}</a> ";   
     }

       echo "<br><br>";
}
2
  • Why not just use implode()? Commented Sep 22, 2011 at 15:55
  • @Rikudo: imploding a multidimensional array doesn't usually turn out too well. Commented Sep 22, 2011 at 15:55

1 Answer 1

1

You don't need to use array_push, since you're only adding one element to the array. You can save the overhead of calling a function by using the syntax:

$people[ $row["id"] ]["tags"][] = array(...);

My answer depends on the necessity of the variables saved from the database. In your supplied code, you're only using the id and tag values from the database in the nested foreach loops. If this is this case, then you can simplify your arrays so you can use implode() on a new tags array. I have not tested this since I do not have your database schema, but I believe it will work.

<?php
$people = array();
$tags = array();

while( ($row = mysqli_fetch_array( $rs, MYSQLI_ASSOC)))
{
    if( !isset( $people[$row['id']]))
    {
        $people[ $row['id'] ] = array( 'id' => $row['id'], 'tag' => $row['tag']);
        $tags[ $row['id'] ] = array();
    }
    $tags[ $row['id'] ][] = $row['tag'];
}

foreach( $people as $pid => $p)
{
    echo "(#{$p['id']}) ";
    echo '<a href="#">' . implode( '</a><a href="#">', $tags[ $p['id'] ])  . '</a>';
    echo '<br /><br />';
}
2
  • how different would it be if I had more than one element in that array (post edited) If it's better I setup a new question plz let me know. Commented Sep 22, 2011 at 20:00
  • 1
    There wouldn't be any changes since you're still not using any more variables in the foreach loop. Commented Sep 22, 2011 at 21:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.