Solved

newbie question - how to create an associative array

Posted on 2014-02-15
11
206 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 51

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 82

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
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 82

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 82

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 82

Expert Comment

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

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.

758 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

20 Experts available now in Live!

Get 1:1 Help Now