SitePoint Sponsor |
|
User Tag List
Results 1 to 7 of 7
Thread: dynamic creation of hash
-
Jun 4, 2006, 06:50 #1
- Join Date
- May 2001
- Posts
- 193
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
dynamic creation of hash
Hi,
How would I or is it possible to:
PHP Code:file.each_line do |line|
line_array = line.split("\t")
line_array[0] = key
line_array[1] = value
# tried this, didnt work
my_hash[key] = []
my_hash[key] << value
end
PHP Code:{"key1"=>["value1", "value1"]}
{"key2"=>["value1", "value1", "value3", "value4"]}
{"key3"=>["value1"]}
-
Jun 4, 2006, 07:39 #2
- Join Date
- Jun 2003
- Location
- Iowa, USA
- Posts
- 3,749
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
how about:
Code:>> my_hash = {} => {} >> my_hash['key'] = ['value1'] => ["value1"] >> my_hash['key2'] = ['val2','val3'] => ["val2", "val3"] >> my_hash => {"key2"=>["val2", "val3"], "key"=>["value1"]}
Jason Sweat ZCE - jsweat_php@yahoo.com
Book: PHP Patterns
Good Stuff: SimpleTest PHPUnit FireFox ADOdb YUI
Detestable (adjective): software that isn't testable.
-
Jun 4, 2006, 07:56 #3
- Join Date
- May 2001
- Posts
- 193
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
sweatje, basically that's what I'm trying to achieve, kind of. But I'm looking to append values to the array not overwrite them with each iteration based on the hash key
-
Jun 4, 2006, 08:06 #4
- Join Date
- Jun 2003
- Location
- Iowa, USA
- Posts
- 3,749
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Appending should work fine, once there is an array there:
Code:>> my_hash['key2'] << 'val4' => ["val2", "val3", "val4"] >> my_hash => {"key2"=>["val2", "val3", "val4"], "key"=>["value1"]}
Jason Sweat ZCE - jsweat_php@yahoo.com
Book: PHP Patterns
Good Stuff: SimpleTest PHPUnit FireFox ADOdb YUI
Detestable (adjective): software that isn't testable.
-
Jun 4, 2006, 08:12 #5
- Join Date
- May 2001
- Posts
- 193
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Right, I guess my problem is when I assign:
my_hash[key] = []
inside of the do block, it overwrites. How can I use a dynamic hash key and append values to it?
-
Jun 4, 2006, 08:15 #6
- Join Date
- Jun 2003
- Location
- Iowa, USA
- Posts
- 3,749
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
perhaps
my_hash[key] = [] unless my_hash.key? key
my_hash[key] << new_valJason Sweat ZCE - jsweat_php@yahoo.com
Book: PHP Patterns
Good Stuff: SimpleTest PHPUnit FireFox ADOdb YUI
Detestable (adjective): software that isn't testable.
-
Jun 4, 2006, 08:28 #7
- Join Date
- May 2001
- Posts
- 193
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Thanks Jason, that's exactly what i was looking for.
Bookmarks