Php 将txt解析为json
我有一个txt文件,看起来像:Php 将txt解析为json,php,json,parsing,Php,Json,Parsing,我有一个txt文件,看起来像: 1 - 10 2 - 20 3 - 30 { "item": "1", "value": "10" }, { "item": "2", "value": "20" }, { "item": "3", "value": "30" }, 我如何制作一个json数组,其外观如下: 1 - 10 2 - 20 3 - 30 { "item": "1", "value": "10" }, { "item": "2", "v
1 - 10
2 - 20
3 - 30
{
"item": "1",
"value": "10"
},
{
"item": "2",
"value": "20"
},
{
"item": "3",
"value": "30"
},
我如何制作一个json数组,其外观如下:
1 - 10
2 - 20
3 - 30
{
"item": "1",
"value": "10"
},
{
"item": "2",
"value": "20"
},
{
"item": "3",
"value": "30"
},
谢谢 您需要逐行读取文本文件,并用分隔符“-”分解该行。然后创建一个可以转换为json的数组
// Open the file to read data.
$fh = fopen('student.txt','r');
// define an eampty array
$data = array();
// read data
while ($line = fgets($fh)) {
// if the line has some data
if(trim($line)!=''){
// explode each line data
$line_data = explode('-',$line);
// push data to array
//array_push($data,array('item'=>trim($line_data[0]),'value'=>trim($line_data[1])));
$data[]=array('item'=>trim($line_data[0]),'value'=>trim($line_data[1]));
}
}
fclose($fh);
// json encode the array
echo $json_data = json_encode($data);
输出:
[{"item":"1","value":"10"},
{"item":"2","value":"20"},
{"item":"3","value":"30"}]
另一种方法解决方案:
您尝试过任何代码吗?您使用的是什么语言?
<?php
// the list in the txt file
$str = "1 - 10
2 - 20
3 - 30";
$so = explode(" ", $str);
$cleanedvalues = array();
foreach ($so as $key => $value) {
if ($value != "") {
$cleanedvalues[] = $value;
}
}
$arrval = array();
foreach ($cleanedvalues as $key => $value) {
if ($value == "-") {
} else {
$arrval[] = $value;
}
}
$tab_keys = array();
$tab_values = array();
foreach ($arrval as $key => $value) {
if ($key % 2 == 0) {
$tab_keys[] = $value;
} else {
$tab_values[] = $value;
}
}
// add the item and value data
$lan = array();
for ($i = 0; $i < sizeof($tab_keys); $i++) {
$lan[] = array(
'item' => trim($tab_keys[$i]),
'value' => trim($tab_values[$i])
);
}
// the final result
echo json_encode($lan);
?>