Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    PHP




Associative Arrays: Are Keys Strings?


I am wondering if it is 'wrong' (although it works) to work with associative arrays like this:

$array[somekey] = blah

instead of specifying the key as a string:

$array["somekey"] = blah

What would you say? What is right, what is wrong from the point of view of correct PHP coding?




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Associative Arrays Keys
I have a some text that i have to sort according to their year. The text is in this format..

A Short Story (2000)
A long time ago (1999)
A list (2004)
Before Time (1999)
Car parts (2004)

so basically i want the output to be..

A long time ago (1999)
Before Time (1999)
A Short Story (2000)
A list (2004)
Car parts (2004)

I thought the way to go about this would be to extract the years and put the whole thing in an associative array with the years as keys, but of course the keys have to be unique so in this case values override each other. PHP Code:

Multibyte Strings As Array Keys
Does this work? Something is breaking when I try to do this, and all I
can think of is that PHP does not allow multibyte array keys.

Associative Arrays...help
Is there any way I can construct an associative array out of 3 other arrays?

Associative Arrays
Basically I am writing a shopping cart from scratch. I can get my first item looking good but I can never add to my cart. If I choose another item it seems to overwrite the first one. Code:

PHP ADODB DB2 Associative Arrays
I know this doesn't -exactly- match php, but its still related, and
adodb doesn't have its own google group yet, so i thought I'd go
generic.

The problem is, I created a nice little script for Oracle using oci8
and tried to convert to db2, but ran into issues. In case you don't
know what ADODB is, checkout http://adodb.sourceforge.net/

The GetAssoc, or SetFetchMode(ADODB_FETCH_ASSOC) methods to get an
associative array from a DB2 database don't function properly. The
result of a simple query, for example:
select firstname, lastname, dob from person
results in an array something like:
Array (
[LASTNAME] => 'Bob'
[DOB] => 'Henry'
[0] => ��-12-01'
)
Now -that- is a real pain, and I've tried looking through the db2
driver, but couldn't pin-point myself where the problem was, as the
ADODB code is a little out of my league, and the complications of the
new 'extension' don't help.

I was just wondering if anyone knows what I'm talking about? Or maybe a
possible solution to the problem? I'd prefer a solution at the base
level, not a 'quick-fix', as I use this library often.

Some further information that might be useful is that i'm running DB2
v8.2 Enterprise, on WinXP (up-to-date). I'm using the latest ADODB
4.8.1 (NOT the extension). And i'm using Apache/2.2.2 + PHP/5.1.4
served on WinXP, same machine as DB2.

Sorting Associative Arrays...
I have an associative array which assigns arrays of 4 values to strings (see the example below):

Array ( [value1] => Array ( [0] => 65 [1] => 2 [2] => 75 [3] => -10 ) [value2] => Array ( [0] => 65 [1] => 2 [2] => 0 [3] => 65 ) [value3] => Array ( [0] => 15 [1] => 2 [2] => 5 [3] => 10 ) )

Up to now, I've been using ksort on the big array and it sorted it by the "value1", "value2", etc., alphabetically. Now, however, I want it sorted numerically by the 4th value of each array inside the big array (the -10, 65, and 10 in the above example).

How would I go about doing this?

Associative Arrays And Loops
I am trying to make database calls on what will potentially be a very large database. I would like to receive query results from the database using mysql_fetch_array() to get an associative array.

Once I have this array, I want to show certain fields using my own formatting.  If there are no fields, I want to show a "No Results" message. My code thusfar looks like this, and it does nothing if there is an invalid database query: Code:

Adding Elements To Associative Arrays
Im trying to generate an associative array from a query. I have tried this and many other combinations but it doesnt work. PHP Code:

Beginner With A Question About Associative Arrays
Is it possible to reference an index of an associative array using a variable? e.g.: If I had an array:

$myArray["first"] = "myValue";

and if I were to declare a variable:

$myVariable = "first";

I can't get PHP to display "myValue" by referencing this index using $myArray[$myVariable];

Interesting Insight Into Associative Arrays Versus Non-associatives...
We should all be familiar with the explode() and implode() functions.

explode("Some String") --> "Some Array"
implode("Some Array") --> "Some String"

The idea is that each function goes back and forth between an array and string, provided you use a common delimiter. Now, let's look at a simple example, before I post my issue. Code:

Strings And Arrays...?
<?php
$var1="abcdefghij";
for ($i=0;$i<strlen($var1);$i++) {
echo $var1[$i].'<br>';}?>

Using that code above... How would i select more than one letter at a time and put it into individual strings for example: If i used that code and wanted to be able to so this:

echo $var1[abc]; ( outputs 'abc' )
echo $var1[def]; ( outputs 'def' )
echo $var1[ghij]; ( outputs 'ghij' )

How To Treat Strings As Arrays?
$string = "some dumb text";
$var = explode(" ", $string);

Would make $var = array("some", "dumb", "text"); but explode doesn't work with "" or a NULL value. I want to break a string up into the individual letters.. How would I go about doing this?

How Do I Turn Strings Into Arrays?
How do I turn a string into array where all the characters in the string to separate values.

Something like this:

$string = "High";

to this:

$array = array('h','i','g', 'h');

Using Array_intersect() Without Keeyping Keys From The Array1, I.e. Re-number Intersect Array Keys.
I only use indexed arrays.

When I use array_intersect function, of $a3 = array_intersect( $a1,
$a2 ), I just need the vales of intersect array and let keys to be
re-numberred from 0.;

I found the intersect array $a3 have the correct values but keep the
keys of $a1. When I use
for loop from $index=0 to sizeof ($a3)-1, by $a3[$index], php reports
"undefined offset " problem.

How can I re-number the keys of $a3 from 0 to sizeof($a3)-1;



Using The $value Of An Associative Array
I am using an associative array to populate one field of a form. I use the $key to obtain the numeric value I want to enter into one of my tables. I use the $value to display in nice text what the numeric key represents. I have no problem entering the $key into the table or displaying the $value on the form. My problem is in displaying the results of the processed form to the user:

My form "action" is "processform". In processform I do the INSERT query and return a message to the user. It is in the message to the user where my problem comes in. I've only captured the $key from the form. How can I capture also the $value from the form post, so that when I display to the user what he or she has chosen on the form, the nice text will display rather than the (to them) meaningless id number? Code:

Associative Array
I have to search a db table, and count distinct records to get some results from a survey we've done. The record needs to be echoed along with the number of times it is recorded. Each field in the table has to be searched individually, so that we can see the answers for each question separately.

I thought that I could do this with one query, maybe 'count distinct', but I couldn't get it to show both the value of the row, and the amount of times that value had been recorded.

So, I have to do 2 queries, one getting the distinct values of the field, the other counting how many times they are recorded. Here's the 2 queries: Code:

Associative Array
I have a list of word/number pairs. I need to retrieve the word that has the highest number associated with it.

I have put this list into an associative array...

$array['apple'] = &#3912;'
$array['orange'] = &#393;'
$array['pear'] = &#3950;'

...and ordered it using arsort() so that "pear" in this case is the first value, then hit a brick wall when I realised that echoing $array[0] didn't work on an associative array. Indeed, why would it? :)

Is there a simple way to retrieve the top value after it's sorted, or do you always need to know the name of the key to manipulate associative arrays?

Else, do I need to look into multidimensional arrays? Something like...

$array[0] = array('apple' => &#3912;');
$array[1] = array('orange' => &#393;');
$array[2] = array('pear' => &#3950;');

At which point, I'm not clear on how this would be sorted based on the values of the nested arrays, and how you would then specify to retrieve the key of the nested array of the first key of the original array!

Associative Array In Class
In PHP Version 4.3.6 I am trying get a value from a class member that
is an associative array...

class MyClass
{
$var row;

function MyClass()
{
$this->$row = array("A"=>"Apple", "B"=>"Bob");
echo "One: " . $this->$row["A"] . "<br>";
echo "Two: " . $this->row["A"] . "<br>";
$cache = $this->$row;
echo "Three: " . $cache ["A"] . "<br>";
}
}

But this is the output...

One: Array
Two:
Three: Apple

How can I get at the value of the associative array without making a
local copy first!

Array_push() With An Associative Array?
Is there a way to add a key/value pair to an associative array? I'm tryint to do this, but it dosn't work.

$author = array();
while ($row = mysql_fetch_array($result)){
array_push($author,$row[id],$row[name]);}

Associative Array Question - Newbie
I am in the process of designing (before coding) my first serious PHP/MySQL application and I have a question about the best way to store information.

The application will allow users to view the voting record of different legislators. I have concluded that the most efficient way to store the data is in two tables: one that has details about each legislator (mp) and another that has the details of each piece of legislation (bill). Each legislators record will have a field that holds info in an associative array in the form (bill ID, vote result). This way, when a new piece of legislation is added to the database, one more value pair (bill ID, vote result) will be added to each legislators voting record field.

My question is two part:

Is this the most efficient way to store the data?

and

I suspect I will have to be using regular expressions to extract and format the data from the MySQL query. Are there some PHP or MySQL functions or syntax I would find useful in this process of retrieving the data? Any online tutorials? (mysql_fetch_array appears to create an array out of two fields - not really what I am looking for...) I realize this is a rather vague question, but if you have any suggestions, please let me know.

Make Associative Array Out Of String
I have a string that look something like this:

$string = "weight, kg|1200|width, mm|220|prize|20000";

and I would like it to an associative array and print keys and value:

weight, kg: 1200
width, mm: 220
prize: 20000

(The string above is fetched from a database)

Anyone have any bright ideas how to do it?

Adding Values Onto An Associative Array...
I'm trying to develop a simple class which through the interface you can add elements to an array. The method I have used to add the elements is setContentFields($name, $field_type), I have used an array counter variable to increment the array index each time. To me this seems like a workaround, and I wondered if there was a more elegant way of doing this.

The class is as follows:

Sorting An Associative Array Of Objects By Value?
I'm trying to sort an array of objects within an object. Included is a
dumbed down example so that we can get at the meat of the issue without
worrying about complexity or validation. Basically, Funk is an object that
has a name (string) and a value(int). FunkThis represents an object
containing a list of Funks, with each key corresponding to the name of the
Funk. I want to sort this list by val, but I get a Warning: usort():
Invalid comparison function error when I run the script. Keep in mind that
this is for PHP 4

I'm open to suggestions to getting this to work.

<?php
class Funk {
var $name;
var $val;
function Funk($name,$val) {
$this->name = $name;
$this->val = $val;
}
function getVal() {
return $this->val;
}

function getName() {
return $this->name;
}
}

class FunkThis {
var $list;
function FunkThis() {
$this->list = null;
}
function add($funk) {
$this->list[$funk->getName()] = $funk;
}

function compareFunks($a,$b) {
$aVal = $a->getVal();
$bVal = $b->getVal();
if ($aVal == $bVal) return 0;
if ($aVal $bVal) return 1;
if ($aVal < $bVal) return -1;
}

function sortByFunk() {
$list = $this->list;
$this->list = uasort($list,"compareFunks");
}

function show() {
print_r($this->list);
}
}

$a = new Funk("A",3);
$b = new Funk("B",7);
$c = new Funk("C",1);
$d = new Funk("D",9);
$e = new Funk("E",6);

$funkthat = new FunkThis();

$funkthat->add($a);
$funkthat->add($b);
$funkthat->add($c);
$funkthat->add($d);
$funkthat->add($e);
$funkthat->sortByFunk();
$funkthat->show();
?>

[smarty] Addressing Associative Array
Given this assoc array:

$dtl_array[0]['uom_array'][0][0]='key1'
$dtl_array[0]['uom_array'][0][1]='value1'
$dtl_array[0]['uom_array'][1][0]='key2'
$dtl_array[0]['uom_array'][1][1]='value2'
$dtl_array[1]['uom_array'][0][0]='key3'
$dtl_array[1]['uom_array'][0][1]='value3'
$dtl_array[1]['uom_array'][1][0]='key4'
$dtl_array[1]['uom_array'][1][1]='value4'

$sample->assign("dtl_array",$dtl_array);
$sample->display();

How could I create a combobox out of $dtl_array in the templates?
The following does not work:

<select name="aname">
{section name=mm start=0 loop=$dtl_array.0.uom_array step=1}
<option value="{$dtl_array.0.uom_array.mm.0}">
{$dtl_array.0.uom_array.mm.1}
{/section}
</select>

Values From Form Via Associative Array
I have a form which has a text field and a select box. There are many other fields also in the form . I need get the value of the text field or the select box, depending on which one has a value. Additionally it has to give the value only from the text field even if there is a selection made from the select box. I know that i can get post values from form like this: PHP Code:

How To Add An Element To The Middle Of An Associative Array ?
I got an array that consists of elements that are arrays also. Now I
wish I could add an element to the middle of it. Let mi give you an
example:

array (
- array(1,15,apple),
- array(2,28,banana),
- array(3,41,orange)
}

I would like to add, let's say, carrot on 2nd position:

array (
- array(1,15,apple),
- array(2,57,carrot),
- array(3,28,banana),
- array(4,41,orange)
}

Array_splice() does not work (or maybe i use it in a wrong way? - it
splits an adding element for, in that case, 3 elements). Array_push()
adds only to the end of an array. can samobody tell me how to add and
element to the middle of an associative array?

Sort An Associative Array Alphabetically
I am working on a product catalog where it displays a product type on a page via the type variable. The products should be displayed alphabetically by $make and $model and i couldn't find any snippets or info other than asort etc. Just curious if anyone else needed such a sort function and how they did it.

ie: product makes Maico, Madsen, Bio-logic etc and their models MA-300, Itera, AC-200. So I would have listings like Maico MA-300, Maico MA-800, Madsen Itera etc., and I need these alphabetical using make and model values. PHP Code:

How To Print A Multidimensional Associative Array?
I have the following associative array:

$user["john"]["mozilla"]=1;
$user["john"]["xmms"]=1;
$user["doe"]["mozilla"]=0;
$user["doe"]["office"]=1;
$user["paul"]["mozilla"]=0;
$user["paul"]["xmms"]=1;
$user["paul"]["office"]=1;

How can I print such an associative array using a loop statement like foreach?

Setting Values In Associative Array To 0
Ive tried almost every combination of while,foreach, key, value ,
array,0 I can some up with

Ive got an associative array that Ive been using as a counter
eg if (blah blah blah )
{$array['beans']++}
elseif (something else){$array['peas']++}
else {$array['carrots']++}

I then want to reset all the values to zero

foreach ($array as $key=>$value)
{ ??????? }
or array_walk ?



XML Formatted String To Associative Array
I'm working on a php socket server for my chat room, and I need to parse some very short XML messages like this:

<msg t="usr"><body a="pubMsg" u="username"><![CDATA[some message]]></body></msg>

Right now I'm using a bunch of substrings (start laughing. lol), but it's very inflexible. However somehow it works...

The problem arises when I try to store user variables (ignore the indents and line brakes, in reality, there will be non of them; we don't want to waste bandwidth)

<msg t="usr">
<body a="updVar" u="username">
<var t="s" n="varname"><![CDATA[some variable]]></var>
<var t="n" n="someNum"><![CDATA[3]]></var>
</body>
</msg>

I have no idea how to parse those stuff from a string to an associative array... What I want is an associative array that I can access those stuff similar to this way:

echo myXML['firstChild']['firstChild']['firstChild']['attributes']['t'];

and it should output "s"

PHP Stops Processing On Multidimensional Associative Array
When using a multidimensional associative array to cross-reference data
in a second, single-dimensional array, PHP stops processing data after
a few iterations. Memory usage according to the task manager doesn't
seem to spike and CPU usage only gets as high as 11 to 13 percent. A
sample script is provided below, any help or alternative solutions are
welcome. (By the way, the script below works fine on Linux with the
same version of Apache and PHP. Possibly a PHP configuration issue?)

Sorting An Associative Multi-Dimensional Array
I would like to sort array below using the last array of a multi-dimensional array. PHP Code:

Printing Out An Associative Array - Whats Wrong?
I have this code segment:

$query = "Select * from Payments order by CustID";
..
.. /* execute the query */
..
if (ora_exec($cursor))
{
$recordset=array();
while (ora_fetch_into($cursor,$recordset,ORA_FETCHINTO_N ULLS|
ORA_FETCHINTO_ASSOC))
{
echo $recordset["CustID"]."<BR>";
echo $recordset["Amount"]."<BR>";
}
}

Gives me the following error
Notice: Undefined index: CustID
Notice: Undefined index: Amount

The table Payments has only CustID and Amount as attributes. is my
usage of the array offset incorrect?

Complex Associative Array To XML FIle And Back
We're using php 4.1 and it doesn't seem to have built in support for
this. Coming from a dotnet background this surprised me...Anyways,
thats a different topic altogether...

I'm looking for a php class that can allow me to save a complex
associative array as an xml file on our server and also be able to read
in back into a complex array when needed. (you'll find an example of
the array below). Because of the complexity if the array, I feel it
would be easier to use this method as opposed to saving to a db.

I know i could write a class to do it, but I'm trying not to reinvent
the wheel. Googleing only refers me to extentions like pear which I
dont want. And I 'm sure someone else has had to do this before.

//ARRAY EXAMPLE ...

ODBC: Fetch Results As Associative Array
Will PHP fetch the results of a query using ODBC as an associative array? I know that MySQL does that, but I couldn't find it for ODBC connections.

POST (or GET) Associative Array To Script From Form
Actually thought I understood this but I can't seem to make it happen this morning, and I can't seem to find a clear simple reference here.

Can I pass an associative array from a form (using either POST or GET) to a .php script all at once, in one simple step?

ie. Say I have the following variable/associative array

$graphtable = Array ( [TESTPHASE] => G085 [GRADE] => 3 [0_LE_1_A] => 0 [1_LE_1_A] => 7 [2_LE_1_A] => 28 [3_LE_1_A] => 22 [4_LE_1_A] => 7 [null_LE_1_A] => 0 [PROTOCOLS] => 64 )

And I pass it as a hidden variable in the following form: ....

Using Max() On Array Keys
i am using an array to store contact data within a session. it looks like this:

$_SESSION['contact'][$key][<content>]

$key counts the set of records, so i have

$_SESSION['contact'][&#390;']
$_SESSION['contact'][&#391;']
$_SESSION['contact'][&#392;']

and so forth. [<content>] stands for the fields containing the actual set of data, which are stored within the [$key]-arrays. at one point i need to find out what the highest value of $key is. running max($_SESSION['contact'])

simply leaves me with "Array()" as the result. what i am doing wrong, and how do i correct it?

Array Keys
is it possible to use only a key in an array meaning:

$arr["a"]="yo";
$arr["bc"]="ygo";
$arr["eea"]="wgyo";
$arr["fa"];
$arr["a"]="yo";

and then somehow get all the keys without and value i tried:

while (list ($key) = each ($arr)) {print $key;}

but i doens't seem to work.

Primary Keys
How is it that even though I have the column "username" in my database set
as a Primary key, using my PHP script to add new users to the database works
without any errors even when signing up using an existing username. I have a
database full of the same usernames!

Array Keys
If I used a "for each" to go through an array or irregularly numbed keys, is there a way to get the key number that the loop is currently on each time?

Shortcut Keys
I would be liek to be able to set up a webpage with shortcut keys so that when certain buttons are presses, a pop up window will open with a designated further page displayed.  Specifically I would like the shortcut keys to be a couple of the function keys, ie f10, f11 and f12. 

Array Keys
Been trying to figure out an array issue.  For some reason when I echo $key it's echoing "Array".  I want it to return the key (in this case adventure). Code:

PHP & MySQ + Unique Keys
I'm trying to write a system thats used for about 50 clients that uses html
forms and php to log details. The problem is that when a client loads the
form page it's given a value which is the last record in a table +1 (i.e. so
its the next record). The problem with that is that a client could sit on
that page for 20 mins (or whatever length of time) and a different client
could use that record number and there what be an error "duplicate key....".
I could use an MySQL UPDATE to lock the record when its issued to each
client and maybe use a timestamp and check if the timestamp is over 10 mins
and delete any records that are over 10mins but there is the possibility of
redundant data (or really useless data, a unique record and a timestamp) in
the table sitting there for 10mins at a time.

Is there an easy way of 'gauranteeing' a client a unique key? So you don't
have to lock the record when the page loads (this also means that when you
refresh the page that the unique key is incremented as you locked the last
record and didn't put anything into the table, so the refreshed page is
issued the next key +1 again).

Automatic Array Keys
My array keys are behaving strangely. In the manual it says calling an array like $array[] = "something" should make the value be put into the next available integer key available. However, my values are being placed with whole sets of blank keys inbetween. Here's what part of the print_r() of the array returns: Code:

Getting MySQL Generated Keys
I am a Java/JSP developer by trade but am currently developing a
MySQL/PHP solution.

In JSP when I run an INSERT statement on the db I am able to
automatically get back a list of any generated keys (without having to
do some sort of subsequent query to get the information).

Is there a PHP equivilent of this?

ActiveRecord And Foreign Keys
I am having trouble wrapping my mind around the ActiveRecord pattern and
foreign keys.

I understand that for each table, there should be a class, and each row
is is effectively an instance.

But, my problem arises when I look at foreign keys and advanced
relationships. For basic foreign keys, I can just automatically
reference to the object. Example:

Table: invoice
id, notes

Table: items
id, cost, invoice_id

When working with an instance with items, I can easily load a new object
called "invoice."

But, what if I am already working with invoice, and I want to load
items? I can't think of any way to abstractly relate the two.

Also, what if I want to two things that are both a "has many"
relationship? For example, if I take users that can have multiple
qualities, I would need three tables: one for users, one for the
qualities, and one to link.

Table: users
id, username

Table: link
id, user_id, quality_id

table: qualities
id, quality_name

PHP MYSQL And Primary Keys
Say I have an ID field in my database that is a primary key and an UNSIGNED AUTO INCREMENTING TINYINT.

It stores range of 0-255. Ok I add a few items to the database, say 240. At a later date I delete a few records, say rows 33, 44, 55, 66, 77, and 240.

So the last record in the database now has an ID of 239, I add another record and it gets assigned an ID of 241?. I then add a few more and it finally reaches ID 255. Now all the ones I deleted previously do not exist. So I try to add another record, will it just get added and assigned the ID of a record that doesent exist such as 33, 44, 55, 66, 77 or 240? If not is there a way around this?

I am pretty new to MySQL and I dont know the answer to this but I know that it could prove to be pretty inefficient if an ID field can hold 255 records but only holds 240. Do you understand what I mean and can anyone answer my question?

Foreach Is Returning Value Of First Key For All Keys
I'm having trouble with the foreach function. I'm using it twice
inside a user defined function with two different arrays, and in the
second instance it's returning the value of the first key for all the
keys. My code is shown below and the problem areas are marked with
comments. In case you're wondering, this script is for generating
sticky checkboxes that include an event handler.

<form>

<?php

if (! is_array($like)) { $like = array(); }

function make_checkbox_click ($name, $query, $options, $onClick) {
foreach ($options as $value => $label) {
printf('<label><input type="checkbox" name="%s[]" value="%s" ',
$name, $value);

# This is the instance of foreach that's not working correctly.
# It's returning the value of the first key for all the keys.

foreach ($onClick as $key => $event) {
printf ('onClick="%s" ', $event);
}

if (in_array($value, $query)) { echo "checked "; }
echo "/> $label</label><br />
";
}
}

# End of user defined function.

$characteristics = array(
'personality' => ' I love their personalities.',
'minds' => ' I admire their minds.',
);

# This is the array that foreach isn't working correctly with.

$charClick = array (
'personality' => "alert('Aren't they the greatest?');",
'minds' => "alert('They're smarter than most people their age.');",
);

make_checkbox_click (posPoints, $posPoints, $characteristics,
$charClick);

?>

</form>

Print Out Array Keys Only
Hi, there are lots of examples that show you how to print array values
given a key. Do you know how to print keys for a given array.

example

$myArray = array('a'=>1, 'b'=>2, 'c'=>3, 'd'=>4);

How do you print 'a', 'b', 'c','d' only without using any loops?


Copyright © 2005-08 www.BigResource.com, All rights reserved