PHP中带文本键的文件到数组?

时间:2013-09-03 21:47:01

标签: php

我一直试图让这个工作一段时间。我有一个使用这种格式的文件:

Value : 1212121212
Value 2 : 1212121212
Value 3 :  1212121212

我需要以这种格式将每个值加上它们加入一个数组。

array {

"Value" => "1212121212"
"Value 2" => "1212121212"
"Value 3" => "1212121212"
}

我可以得到这样的价值:echo $Array[0]['Value'];

我将如何做到这一点?谢谢。也:

我是PHP的初学者,所以如果你能用你的答案添加一些文档,那就太好了。谢谢!

2 个答案:

答案 0 :(得分:3)

在评论中找到所有解释。

// this line reads the file into an array, where each element represents a line
$lines = file('path/file');

// initiate a blank array
$result = array();

// run through all lines
foreach ($lines as $line) {
    // explode each line into a new array containing the key and the value
    $temp = explode(' : ', $line);
    // in the result array set the key and the value accordingly
    $result[$temp[0]] = $temp[1];
}

// will print the value of 'Value'
print $result['Value'];

以下是此示例中使用的所有内容的一些链接:

file / explode / foreach / arrays

答案 1 :(得分:1)

也许这会有所帮助:

$data = array();

// file() returns an array with all lines of the file.
// iterate over them:
foreach(file('your.file') as $line) {
    // split the line by a colon
    $record = explode(':', $line);
    // add the new index to $data
    $data [trim($record[0])] = trim($record[1]);
}

var_dump($data);