Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 220
  • Last Modified:

newbie question - how to create an associative array

I have seen things like:
      $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

But I have not been able to find examples on how to create an associative array dynamically, In other words, I need to add items to a new array while looping through a recordset.

    while($row = mysql_fetch_assoc($res))
    {
       //  add the name and age to array
    }
0
KCTechNet
Asked:
KCTechNet
1 Solution
 
Dan CraciunIT ConsultantCommented:
You normally add like this:
$array[$key] = $value

In your example it makes no sense adding to the $row array.
It's only read from a mysql query, and adding to it won't have any effect on the query.

HTH,
Dan
0
 
Julian HansenCommented:
Firstly

It appears you are using the MySQL library to access your database. This has been deprecated and will no longer be supported in future versions of PHP. Consider learning MySQLi or PDO instead

Secondly,

If you are using fetch_row_assoc the returned array is already an associative array - why do you need to create a second associative array if you have it already

To create an associative array is simply defining the key

$arr = array();
$arr['firstname'] = 'Bob';

Open in new window


You can find more info at PHP.net and W3 Schools
0
 
Dave BaldwinFixer of ProblemsCommented:
In PHP, all arrays are 'associative' with a 'key' and a 'value'.  If you don't create a key value, PHP will create one that is an integer that doesn't already exist in the array.  The man page for the 'array type' has some info you should probably read because it isn't all obvious.

http://www.php.net/manual/en/language.types.array.php
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
KCTechNetAuthor Commented:
where I was hoping to go with the $row was something like

while($row = mysql_fetch_assoc($res))
    {
       $fieldArray[] = array('fieldName' => $row["fieldName"], 'fieldWidth' => $row["columnWidth"]);
    }

The reason I want to put it in an array is because I will later close the connection but want to access the values in the array.  So I would later loop through $fieldArray and want to get:
$fieldArray[0] fieldName is 'field1'
$fieldArray[0] fieldWidth is 50
$fieldArray[1] fieldName is 'field2'
$fieldArray[1] fieldWidth is 150

etc..

I have been playing with the 'while' loop code in this post and I think it is loading the array, but now I don't know how to get the values back out
0
 
KCTechNetAuthor Commented:
perhaps a good example what what I want to do is:
http://www.w3schools.com/php/showphp.asp?filename=demo_func_array4

When I try that it loops 14 times, which is correct, but  I get:
Key=0, Value=Array
Key=1, Value=Array
Key=2, Value=Array
Key=3, Value=Array
Key=4, Value=Array
Key=5, Value=Array
Key=6, Value=Array
Key=7, Value=Array
Key=8, Value=Array
Key=9, Value=Array
Key=10, Value=Array
Key=11, Value=Array
Key=12, Value=Array
Key=13, Value=Array
0
 
Dave BaldwinFixer of ProblemsCommented:
In "$row = mysql_fetch_assoc($res)", $row IS an array.  What you are showing above is correct.  To access the elements, you

echo $fieldArray[0]["fieldName"]." ".$fieldArray[0]["columnWidth"];
echo $fieldArray[1]["fieldName"]." ".$fieldArray[0]["columnWidth"];
echo $fieldArray[2]["fieldName"]." ".$fieldArray[0]["columnWidth"];
.
.
.
echo $fieldArray[13]["fieldName"]." ".$fieldArray[0]["columnWidth"];

Open in new window

0
 
Dave BaldwinFixer of ProblemsCommented:
I made a mistake above.  Both elements on each row should have the same number.

Here's a demo of doing it both ways.  I save the '$row' to an array called $fieldArray[] the first time thru and then use a 'foreach' to go thru it a second time.  As shown here https://www.dibsiam.com/dbc-array.php , both ways produce the same results.  You would have to replace my access info and my fields with yours to get it to work on your database.
<?php 
// DB configuration
$dbhost = "12.34.56.78";    // Your database server
$dbuser = "youruser";      // Your db username
$dbpass = "yourpass";      // Your db password
$dbname = "yourbase";      // Your database name
$dbtable = "yourtable";  //"websitelist";

$dbh = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Dave's dbCheck PHP MySQL $rows to Array</title>
<meta name="author" content="Dave Baldwin" />
<meta name="description" content="Dave's Music Pages" />
</head>
<body>
<table border="0" cellpadding="1" cellspacing="1" width="800px" bgcolor="#77cc77">
<tbody>
<?php 

$result = mysql_query("SELECT ent_num, Sortname, Descript, Cat FROM $dbtable ORDER BY ent_num LIMIT 10");
if (!$result) {
   echo 'Could not run query: ' . mysql_error();
   exit;
}

while ($row = mysql_fetch_assoc($result)) {
$fieldArray[] = $row;
echo '<tr>';
echo '<td>'.$row['ent_num'].'</td>';
echo '<td>'.$row['Sortname'].'</td>';
echo '<td>'.$row['Descript'].'</td>';
echo '<td>'.$row['Cat'].'</td>';
echo '</tr>';
}
?>
</tbody> 
</table>
<hr>
<table border="0" cellpadding="1" cellspacing="1" width="800px" bgcolor="#77cc77">
<tbody>
<?php 
foreach($fieldArray as $row) {
echo '<tr>';
echo '<td>'.$row['ent_num'].'</td>';
echo '<td>'.$row['Sortname'].'</td>';
echo '<td>'.$row['Descript'].'</td>';
echo '<td>'.$row['Cat'].'</td>';
echo '</tr>';
}

 ?>
</tbody> 
</table>

</body>
</html>

Open in new window

0
 
KCTechNetAuthor Commented:
I have several recordsets I loop through and I re-use $row.  I didn't even think that I don't need to create another array, just change it to a name that is not going to get destroyed.

so I changed it to:
$fieldArray=mysql_fetch_assoc($res);

then later, I am trying to access it like this:
                     foreach ($fieldArray as $k) {
                    echo $fieldArray[$k]["fieldName"].": ".$fieldArray[$k]["columnWidth"]."<br/>";
                }

but I get the error:  Warning: Invalid argument supplied for foreach() in /home/uniqueda/public_html/xtime/gridDisplay.php on line 58
0
 
KCTechNetAuthor Commented:
oops..didnt see your last post...let me review....
0
 
KCTechNetAuthor Commented:
that was it... perfect.

thanks
0
 
Dave BaldwinFixer of ProblemsCommented:
You're welcome, glad to help.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now