Page 1 of 1

Array from file

Posted: Tue Apr 20, 2004 12:11 pm
by Chris Corbyn
HI,
I've got a txt file that contains something like this:
"blue_red" => "chips_chocolate", "orange_yellow" => "bananas_grapes", "pink_green" => "cakes_biscuits",
This is what i would like to create an array from. So the first key would be ['blue_red'] with a value "chips_chocolate".

Is there a way to do this?

I tried

Code: Select all

$array = array (file_get_contents('arraycontents.txt'));
print_r($array);
But the output was
Array ( [0] => "blue_red" => "chips_chocolate", "orange_yellow" => "bananas_grapes", "pink_green" => "cakes_biscuits", )
It's just taking the entire lot as key[0].

Thanks :-)

Posted: Tue Apr 20, 2004 12:18 pm
by xisle
could you use serialize() to create the file and unserialize() to reconstruct the array? Or is this something you do not create...

Posted: Tue Apr 20, 2004 12:18 pm
by mudkicker
i think you should read the file and take all keys and values seperately..

i meant:

array.txt

KEY1 VALUE1
KEY2 VALUE2
.
.
.
.

like this...

Posted: Tue Apr 20, 2004 12:21 pm
by Chris Corbyn
mudkicker, could you please explain a bit better?

Posted: Tue Apr 20, 2004 12:23 pm
by Chris Corbyn
Ok, been looking at serialize. It looks promising but I'm not quite sure how i would put it into action. The file is a file that I create yes so technically I could do that.

Posted: Tue Apr 20, 2004 12:26 pm
by mudkicker
well if you can, preapare a text file like this

key1#value1
key2#value2
key3#value3
...etc

every line has a key and a value seperated by a #.

so do that :

Code: Select all

<?
$array = array();
$file = file("array.txt");
foreach ($file as $f) {
$buf = explode("#",$f);
$array[$f[0]] = $f[1];
}
?>
i didnt test it but it should work..

Posted: Tue Apr 20, 2004 12:27 pm
by magicrobotmonkey
first explode it by comma then explode those by => then build your array

http://us3.php.net/manual/en/function.explode.php

like

Code: Select all

<?php

$indeces = explode(",", file_get_contents('arraycontents.txt')); 
$array = array();

foreach($indeces as $index){
  $temp = explode(" => ", $index);
  $array["$temp[0]"] = "$temp[1]";
}

?>

Posted: Tue Apr 20, 2004 12:43 pm
by Chris Corbyn
magicrobotmonkey, explode() did the trick. thanks. :-)