如何从txt文件中提取数组。
我使用file_put_contents将数组放入文本文件中。
Array
(
[0] => Array
(
[0] => AMDSempron 145
[1] => 860,000
[2] => 910,000
)
[1] => Array
(
[0] => IntelCore 2 Quad Q8200 2.33GHz 4MB L2 Cache
[1] => 1,800,000
[2] => 1,800,000
)
[2] => Array
(
[0] => IntelCore i7-920 Processor (8M Cache, 2.66 GHz, 4.80 GT/s
[1] => 3,300,000
[2] => 3,300,000
)
[3] => Array
(
[0] => IntelCore⢠i5-3450 Processor -6M Cache, up to 3.50 GHz
[1] => 5,600,000
[2] => 6,800,000
)
[4] => Array
(
[0] => Intel® Core⢠i3-530 Processor -4M Cache, 2.93 GHz
[1] => 2,350,000
[2] => 2,380,000
)
}
然后将数组输入到文本文件。
此
file.txt的
Array
(
[0] => Array
(
[0] => AMDSempron 145
[1] => 860,000
[2] => 910,000
)
[1] => Array
(
[0] => IntelCore 2 Quad Q8200 2.33GHz 4MB L2 Cache
[1] => 1,800,000
[2] => 1,800,000
)
[2] => Array
(
[0] => IntelCore i7-920 Processor (8M Cache, 2.66 GHz, 4.80 GT/s
[1] => 3,300,000
[2] => 3,300,000
)
[3] => Array
(
[0] => IntelCore⢠i5-3450 Processor -6M Cache, up to 3.50 GHz
[1] => 5,600,000
[2] => 6,800,000
)
[4] => Array
(
[0] => Intel® Core⢠i3-530 Processor -4M Cache, 2.93 GHz
[1] => 2,350,000
[2] => 2,380,000
)
}
现在我该如何提取? 我写了这个代码。
<?php
file_put_contents('array.txtl', print_r($data, TRUE));
$arrtxt = file_get_contents('array.txt',treu);
//Select Name and Price from array
$par1= array_column( $arrtxt, 0);
$par2 = array_column( $arrtxt, 1);
//Combine Name and Price array
$c = array_combine($par1, $par2);
foreach($c as $name=>$price){
echo 'Name:'.' '.$name.'<br />'.'<hr>'.PHP_EOL;
echo 'price:'.' '.$price.'<br />'.'<hr>'.PHP_EOL;
}
?>
但是给这个错误:
array_column()期望参数1为数组,资源在第28行的C:\ wamp \ www \ curl \ index.php中给出
答案 0 :(得分:0)
尝试使用以下代码:
file_put_contents('array.txt', json_encode($data));
$arrtxt = file_get_contents('array.txt');
$newarr = json_decode($arrtxt);
print_r($newarr); //this will output an array
答案 1 :(得分:0)
您可以稍微修改一下您的文本文件(请注意,PHP&#39; s数组创建数组()函数的名称是全小写的):
<?php
$myArray = array([0] => array([0] => AMDSempron 145
[1] => 860,000
[2] => 910,000
)
[1] => array([0] => IntelCore 2 Quad Q8200 2.33GHz 4MB L2 Cache
[1] => 1,800,000
[2] => 1,800,000
)
[2] => array([0] => IntelCore i7-920 Processor (8M Cache, 2.66 GHz, 4.80 GT/s
[1] => 3,300,000
[2] => 3,300,000
)
[3] => array([0] => IntelCore i5-3450 Processor -6M Cache, up to 3.50 GHz
[1] => 5,600,000
[2] => 6,800,000
)
[4] => array([0] => IntelCore i3-530 Processor -4M Cache, 2.93 GHz
[1] => 2,350,000
[2] => 2,380,000
)
);
?>
然后,在你要使用这个数组数组的php文件中,只需执行以下操作:
include("array.txt");
和&#34; $ myArray&#34;在那之后到处都会存在&#34;包括&#34;,并且已经是数组。