0

code:

$persons = array(); $tags = array(); while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { if(!isset($persons[$row["id"]])) { $persons[$row["id"]]= $row; $tags[ $row['id'] ] = array(); } $tags[ $row['id'] ][] = $row['tag']; } foreach($persons as $pid=>$p){ $tag1 = $p["tag"]; $tag1ish = $tags[$p['id']]; } 
2
  • 3
    You mean how to get the first element of the array? Commented Oct 2, 2011 at 22:30
  • @mosty mostacho yes. Get the first element of the tags array Commented Oct 2, 2011 at 23:55

5 Answers 5

2
foreach($persons as $pid=>$p){ $tag1 = $p["tag"]; $tag1ish = $tags[$p['id']]; /* to get the first tag, there are many options e.g.: */ $first_tag = $tag1ish[0]; // given u use [] syntax as above. } 
Sign up to request clarification or add additional context in comments.

Comments

1

I think the clarification didn't help much :P Anyway, I'd reccomend to order the tags by ID then (or at least alphabetically). So the order of the tags will be the same and accessing the first element of the array would return always the same tag.

2 Comments

hmmm this is what I want but I can't think of it right now. Thanks for clearing it up a bit. I do have my ranks that numbers my tags from 1 to 4.
I'm not sure about ranks, but IDs are unique, that is your best option. Probably adding it in the SQL code or even sorting the array in PHP might do the trick.
1

You could avoid calling a foreach and just use the first element

$tag1 = $persons[0]["tag"]; 

or use current:

$tag1 = current($persons); 

Comments

0

if i understand well, you can use the reset() function. It received an array as argument and returns the first element.

2 Comments

no, reset — Set the internal pointer of an array to its first element
and returns the value of the first array element.
0
foreach($persons as $pid=>$p){ // is this what you mean..? $theTagYouWant = $tags[0]; $tag1 = $p["tag"]; $tag1ish = $tags[$p['id']]; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.