Solved

newbie question - how to create an associative array

Posted on 2014-02-15
11
207 Views
Last Modified: 2014-02-16
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
Comment
Question by:KCTechNet
11 Comments
 
LVL 34

Expert Comment

by:Dan Craciun
ID: 39862306
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
 
LVL 52

Expert Comment

by:Julian Hansen
ID: 39862329
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
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 39862356
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
 

Author Comment

by:KCTechNet
ID: 39862368
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
 

Author Comment

by:KCTechNet
ID: 39862370
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 39862375
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
 
LVL 83

Accepted Solution

by:
Dave Baldwin earned 500 total points
ID: 39862387
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
 

Author Comment

by:KCTechNet
ID: 39862393
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
 

Author Comment

by:KCTechNet
ID: 39862395
oops..didnt see your last post...let me review....
0
 

Author Comment

by:KCTechNet
ID: 39862400
that was it... perfect.

thanks
0
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 39862406
You're welcome, glad to help.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now