SitePoint Sponsor |
|
User Tag List
Results 1 to 8 of 8
-
Jan 24, 2002, 14:53 #1
- Join Date
- Sep 2001
- Location
- Bellingham, WA
- Posts
- 14
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Iterating through an associative array.
I have an associated array that I've have created from data out of a mysql query.
When using the following code I get one extra entry output that there should be:
PHP Code:for( $i = 0; $i < count( $myarray ); $i++ )
{
echo( $myarray[$i]["text"] );
}
thanks,
greg
-
Jan 24, 2002, 16:52 #2
- Join Date
- Nov 2001
- Location
- Montreal
- Posts
- 794
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
foreach is your friend. (-:
http://php.net/foreach
PHP Code:foreach ($myarray AS $element) {
echo $element["text"]
}
-
Jan 24, 2002, 17:51 #3
- Join Date
- Sep 2001
- Location
- Bellingham, WA
- Posts
- 14
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
is this going to work for a multidimensional array that is a class member. the real code that i'm using looks more like this:
PHP Code:for( $i = 0; $i < count( $this->vehicles ); $i++ )
{
$query = "select description from make where makeid = ".$this->vehicles[$i]["makeid"]." limit 0, 1";
$result = mysql_query( $query, $db );
if( $result )
{
$row = mysql_fetch_array( $result );
$this->vehicles[$i]["make"] = $row["description"];
}
else
{
$this->vehicles[$i]["make"] = "Unknown";
}
}
-
Jan 25, 2002, 02:47 #4
- Join Date
- Jan 2002
- Posts
- 11
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Not sure I understand the question, but your code can be greatly improved. No need for that for loop, instead:
PHP Code:$vset = Array();
foreach($vehicles as $vehicle) {
$vset[] = $vehicle["makeid"];
}
$query = "SELECT description FROM make WHERE makeid IN (".join(',', $vset).")";
-
Jan 25, 2002, 10:50 #5
- Join Date
- Sep 2001
- Location
- Bellingham, WA
- Posts
- 14
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
$vehicles already has all of the vehicles in it, it just has makeid and modelid instead of the text description of them. That is what this is for, to grab the make, and later the model and place them in the array as well.
greg
-
Jan 26, 2002, 03:45 #6
- Join Date
- Jan 2002
- Posts
- 11
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Yes but there's certainly no point in executing one query per vehicle when you can use a single query to achieve the same.
-
Jan 26, 2002, 13:18 #7
- Join Date
- Sep 2001
- Location
- Bellingham, WA
- Posts
- 14
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
I guess I'm not clear on how to achieve this.
-
Jan 27, 2002, 06:36 #8
- Join Date
- Jan 2002
- Posts
- 11
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Just look at the code I posted. I extract all the vehicle id values, and then output this so that the query is like:
SELECT * FROM tablename WHERE id IN (1,2,3);
(This query will select entries with id 1, 2 or 3 if they exist).
Bookmarks