OfirH
OfirH

Reputation: 657

Foreach with 2D arrays

I'm trying to pull out value of an 2D array with foreach. I have this array for example:

$ud['prc']['col1']
$ud['prc']['col2']
....

My loop:

foreach ($ud['arc'] as $name => $rank)  {
    if ($name != 'user_ID') {
        echo "<tr><td>{$name}</td><td>{$rank}</td></tr>";
    }
}

This code for some reason printing first a table row with the number of the array (name as '0' ($ud['prc']['0']) instead of its real name 'col1')

Instead of printing me:

 <tr><td>col1</td><td>value of col1</td></tr>
 <tr><td>col2</td><td>value of col2</td></tr>
 <tr><td>col3</td><td>value of col3</td></tr>

It prints this:

 <tr><td>0</td><td>value of col1</td></tr>
 <tr><td>col1</td><td>value of col1</td></tr>
 <tr><td>1</td><td>value of col1</td></tr>
 <tr><td>col2</td><td>value of col2</td></tr>
 <tr><td>2</td><td>value of col1</td></tr>
 <tr><td>col3</td><td>value of col3</td></tr>

I really hope I explained myself good enough, if not comment please and tell me what you didn't understood so I could explained it to you.

I am using this in conjunction with MySQL

Here is my MySQL code:

The $ud['arc'] array contains this:

$arc_q= mysql_query("SELECT * FROM arc WHERE user_ID='$id'"); 
$arc = mysql_fetch_array($arc_q); 
$ud['arc'] = $arc;

Upvotes: 0

Views: 88

Answers (3)

robi
robi

Reputation: 123

Your $ud array isn't an associative array, so it is indexed by numbers (0..n) and strings also, not only by strings ('prc', etc..). So your result array has double values.

If your array is generated from an SQL query, then you should use:

$ud = mysqli_fetch_assoc() instead of mysqli_fetch_array()

Upvotes: 1

Vinicius Monteiro
Vinicius Monteiro

Reputation: 585

As its array comes from a query you have two options:

1 - Adding MYSQL_ASSOC parameter in "mysql_fetch_array" function

2 - Validate that the key is integer and skip

I personally prefer the first by not needing to create more code

Upvotes: 0

php-dev
php-dev

Reputation: 7156

Change your

$arc = mysql_fetch_array($arc_q);

to

$arc = mysql_fetch_assoc($arc_q);

Hope it helps.

Upvotes: 0

Related Questions