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




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!




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
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!

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: ....

Class Array To Sql
I've got a class with an array in it, and some data in the array.

I instantiate the class as myArray class, and pass it to a function, the function uses the array in the class as input for a mysql database. The problem is the sql wont input the data. I can insert into the database via sql local variables and local arrays and class variables but not class arrays? if i save the class array to a local variable and insert that into the sql then that works, but it wont go straight in? I imagine this has to do with passing the array by refrence rather than by value as i get "array[]" as the value in the database but i can't be sure. Code:

Can I Have An Array As A Class Variable?
class MyClass
{
var $start;
var $finish;
function MyClass($start, $finish)
{
$this->start = $start;
$this->finish=$finish,
$this->sensor_array = get_sensor_array();
}
function get_sensor_array
{
so some stuff to populate $this->sensor_array;
return array($this->sensor_array);
}
}

another question i have,
why do i need to declare variables with the var if i can declare them
in the constructor without it ?

just a couple of questions.
if you have read this far,

Bug With Array Declaration In Class
Can someone confirm this problem:

This works:

var $x = array(
"x" => "x".
"y",
"y" => "a".
"b"
);
}

var_dump($x);

But this doesn't work:

class g{
var $x = array(
"x" => "x".
"y",
"y" => "a".
"b"
);
}

$g = new g();

var_dump($g->x);

It throws

Parse error: parse error, expecting `')'' in x.php on line 5

I know I have an outdated version of PHP (4.3.2), but it is compiled
with a special MSSQl extension and I cannot seem to compile the patch
with 4.3.3 and 4.3.4. The patch reads the milliseconds for dates.
There's a workaround, but it would involve heaps of testing again.

Just wanted to see, if its worth going to a different version.

How To Use A Class Variable Array
Well i try to use $this->array[0] but it will always end up printing Array[0] because it sees it as though i were call $this->array and [0] seperatly. What can i do to make the script see it as one? Is there anything i can do?

Instanciate Class From Array
I'm searching a way to instanciate php5 class which names are
contained in a array.
Something like:
$class_name = myArray['class'] ;
$object = new $class_name()... of course, this syntax won't work..
that was just to explain :)
I use the magic __autoload function to include required classes, but I
can't find a way to instanciate a class from a string contained in a
array..

Passing An Array To Class
I'm working on learning OOP with php, and in the process I'm stuck trying to send an array to a class (which performs a function) to create a page with a menu system. I'm only in the beginning stages, as I can't seem to figure out why everything works UNTIL I send this to the class. Here's the general idea: (code to follow)

index.php consists of include files to add all functions and classes, then has a few variables that user can change: $title, $menu (array where I'm having problems), $body. Then I create a new variable off the class page as such: $b = new page("$title", "$menu", "$body");

The page class is working fine, until I try to give an array. I can echo out $title & $body fine, and I can echo out a non-array of $menu as well. When I echo out $menu I get "Array", when I echo out $menu[0] I get "A", $menu[1] is "r" etc (spells out Array).

The page class has a construct which sends each variable to the proper function, and everything else works. It is just obvious that the class isn't receiving an actual array, but the word "Array" instead. I can call the function from the index.php page (do_menu($menu)) and it will spit out the array, but once it goes to the class it is lost.

Sooo... all that 'splaining and I'm wondering if it's even possible to hand an array off to a class?!? Code:

Array As Class Property Question
I am using PHP 4 with classes but I have come across a slight problem...
I can't declare an array as a property of a class, ie,

class clTest
{
var $a[];

clTest()
{
// ...some stuff here...
}

DoAdd($name, $content)
{
$this->a[] = array("name" => $id, "content" => $content);
}
}

This produces the error,
Parse error: parse error, expecting `','' or `''' in
/srv/www/htdocs/test/table.php on line 10

line 10 is the "var $a[]".

Am I missing something out or doesn't PHP4 allow arrays as properties?

ACCESS VALUES WITHIN CLASS WITHIN AN ARRAY
I have the following construct (printed with print_r):

Array
(
[0]=> Classes Object
(
[_my_id] => 001
[_my_name] => John
)
[1]=> Classes Object
(
[_my_id] => 003
[_my_name] => Jill
)
)

What is the syntax to access _my_id and _my_name in for loop.

I have this but it doesn't work:
-for ($I = 0; $I < count($myarrays_name); $I++) {
print $myarrays_name[$I]=>Classes->_my_id
}

Extending An External Array Into A Class
I have three files. One stores settings into an array. Another is a class. And yet another is the test page. PHP Code:

How Can I Make An Array Available To All Functions With In A Class
I unsuccsessfully tried the following:

class myclass {
$this->$myvariable[1]=20;
$this->$myvariable[2]=20;

function myfuction1{
print $this->$myvariable[1];
;
}

function myfuction2{
print $this->$myvariable[2];

}

} //end of myclass;

Display Array Values In A Class
I'm trying to diplay values from an HTML mutiple select list in a class. I'm trying to pass the array of selected values in the same manner as the strings in the other sets and gets in the code below. But I don't seem to be getting an array when I try to use getArrayCities. How do I pass the array and display the array values by using getArrayCities? Code:

How To Print Sub Class Of Asso Array...
How to get all information by using while loop...

$Student = array( ....

Accessing Array Returned By Function From Class
I have a function in a class that returns an array of query results, but I can't for the life of me use the array results once retrieved from the class... here's the code I have so far: PHP Code:

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] => &#55614;&#57108;-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.

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:

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:

Defining A Class/instantiating Object Inside A Method Of Another Class
I have a class. Inside the class I have a method that reads a text file.
In the text file I have a class name and a file name where that class is
defined. Now, I need to instantiate an object of that class, the problem
being that at the time I find out the class name and the file name, I'm
inside a method of another class. Well, let me just type up a little
example:

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?

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];

Child Class Member's Iteration By Parent Class
I have a class that has a few private members. Is there a way to create a function in its parent class that can access its (child's) private members.

With the following code I am able to get only the public and protected members.

class parentIter {

function iterateProps ( ) {
foreach ( $this as $propName => $propValue ) {
echo "<br>$propName => $propValue" ;
}
}
}

class childIter extends parentIter {
protected $var1 = 'protected var' ;
private $var2 = 'private var' ;
public $var3 = 'public var' ;

function iterateProps ( ) {
parent::iterateProps () ;
}
}
$obj = new childIter () ;
$obj->iterateProps ( ) ;

PHP5: Can A Class Inherit Initialized Classvariable From Another Class?
I got following problem trying to inherit a variable from another class

class Core
{
public $obj;

function initialize($obj)
{
$this->obj = $obj;
}

}

class test extends Core
{
function test()
{
echo $this->obj;
// or
echo parent::$obj;
// ??
}

}

$core = new Core
$core->initialize('hello');

$test = new test
$test->test();

As far as what I would like to get, I would see 'hello', but instead I
get following error:
Fatal error: Access to undeclared static property: Core::$obj (echo
parent::$obj;)
After declaring $obj as public and static I don't get any result as
well..
Is it possible to inherit already initialized variables from a
different class or are there design patterns who could do something
like that? I hope it is clear where I want to go with this..
I am doing this because I can't give the class test any parameters
because it could be extended (class woow extends test). Also the amount
of variables is not certain and there might be lots of classes needing
to inherit the variables. That would mean that I would have to change
every class if a parameter would change..

Access Class Member Function Without Instantiating Class?
I need to access a class member function from outside the class, and hopefully without having to instantiate the class if possible?

I have an HTML form <select> and each <option> item is being pulled from an array stored in a mysql db.  But I'm doing this independently of the normal purpose of the class itself, I just want to use that member function.

Modify A Function Of A Parent Class From The Child Class ?
How do i modify a function of a parent class from the child class ?

Calling Class Method Of Variable Class.
Yes, it's the week of OO here in c.l.php

If I want to call the method a class (not an object), one normally uses:
classname::method();

which works fine.

However, what if I don't know the classname yet?
$classname::method();
doesn't work, neither does
{$classname}::method();

I've got solved it like this now:
call_user_func(array($classname,'method'));


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