General Community > Scripting Help
list to array with defined keys
Anguz:
if I have this
--- Code: ---$list = "
k1, v1\n
k2, v2\n
k3, v3";
--- End code ---
I know that exploding it I can save each line in an array, but how can I use the first value in each line as the key? like this
--- Code: ---'k1' => "v1",
'k2' => "v2",
'k3' => "v3"
--- End code ---
Parham:
rough thinking of what i came up with, but it keeps adding an empty first element.. i have no idea where it's coming from:
--- Code: ---<?php
$list = "
k1, v1\n
k2, v2\n
k3, v3";
foreach (explode("\n", $list) as $element) {
$element = trim($element);
list($key,$value) = explode(",", $element);
if (!isset($array)) {
$array = array($key => $value);
} else {
$array += array($key => $value);
}
}
//testing
foreach ($array as $a => $b) {
print "$a - $b\n";
}
?>
--- End code ---
chris:
--- Quote from: Parham on August 28, 2003, 01:39:45 PM ---rough thinking of what i came up with, but it keeps adding an empty first element.. i have no idea where it's coming from
--- End quote ---
quite simple ;D
replace
--- Code: ---$list = "
k1, v1\n
k2, v2\n
k3, v3";
--- End code ---
with
--- Code: ---$list = "k1, v1\n
k2, v2\n
k3, v3";
--- End code ---
and it doesn't happen ;D ;D ;D
Anguz:
aaaa I see... exploding the exploded does the trick
why did you write this line like this?
--- Code: ---$array += array($key => $value);
--- End code ---
the "+=" adds to the existing array instead of overwritting it?
Parham:
--- Quote from: Christian Land on August 28, 2003, 02:49:41 PM ---
--- Quote from: Parham on August 28, 2003, 01:39:45 PM ---rough thinking of what i came up with, but it keeps adding an empty first element.. i have no idea where it's coming from
--- End quote ---
quite simple ;D
replace
--- Code: ---$list = "
k1, v1\n
k2, v2\n
k3, v3";
--- End code ---
with
--- Code: ---$list = "k1, v1\n
k2, v2\n
k3, v3";
--- End code ---
and it doesn't happen ;D ;D ;D
--- End quote ---
I'm a complete idiot, TOTALLY didn't see that first newline...
* Parham walks away with a moronic feel :P
Navigation
[0] Message Index
[#] Next page
Go to full version