PHP-文件到关联数组,附加1个键和两个值
我有一个文本文件,其中包含:PHP-文件到关联数组,附加1个键和两个值,php,arrays,key,associative-array,key-value,Php,Arrays,Key,Associative Array,Key Value,我有一个文本文件,其中包含: email:number1:number2 email:number1:number2 email:number1:number2 email:number1:number2 我需要做的是将它们存储在一个关联数组中,其中电子邮件是键,数字是值 如何使用PHP实现这一点 以下是我迄今为止的尝试 <?php // file path $file = 'orderdata'; // open the file and get t
email:number1:number2
email:number1:number2
email:number1:number2
email:number1:number2
我需要做的是将它们存储在一个关联数组中,其中电子邮件是键,数字是值
如何使用PHP实现这一点
以下是我迄今为止的尝试
<?php
// file path
$file = 'orderdata';
// open the file and get the resource handle with errors suppressed
$handle = @fopen($file,'r');
// array to hold our values
$params = array();
if($handle)
{
// if handle is there then file was read successfully
// as long as we aren't at the end of the file
while(!feof($handle))
{
$line = fgets($handle);
$temp = explode(':',$line);
$params[$temp[0]] = $temp[1];
}
fclose($handle);
}
function search_array ( array $array, $term )
{
foreach ( $array as $key => $value )
if ( stripos( $value, $term ) !== false )
return $key;
return false;
}
?>
试试这个
// file path
$file = 'orderdata.txt'; // REMEMBER TO MENTION THE CORRECT FILE WITH EXTENSION
// open the file and get the resource handle with errors suppressed
$handle = @fopen($file,'r'); // DONT USE @ while at development since it will suppress errors
// array to hold our values
$params = array();
if($handle)
{
// if handle is there then file was read successfully
// as long as we aren't at the end of the file
while(!feof($handle))
{
$line = fgets($handle);
$temp = explode(':',$line);
$params[$temp[0]][] = $temp[1];
$params[$temp[0]][] = $temp[2];
}
fclose($handle);
}
检查脚本中的$file='orderdata.txt'
,并添加适当的扩展名,只有当php文件和orderdata
文件位于同一路径时,这才有效。如果没有,请提供文件的绝对路径并重试
如果输入是这样的
test1@example.com:1:11
test2@example.com:2:12
test3@example.com:3:13
test4@example.com:4:14
然后上面的脚本将输出如下
Array
(
[test1@example.com] => Array
(
[0] => 1
[1] => 11
)
[test2@example.com] => Array
(
[0] => 2
[1] => 12
)
[test3@example.com] => Array
(
[0] => 3
[1] => 13
)
[test4@example.com] => Array
(
[0] => 4
[1] => 14
)
)
到现在为止你都试了些什么?展示你的code@shatheesh我已经用我到目前为止尝试过的方法编辑了这篇文章:-)你面临着什么错误?$params的o/p是什么
我并没有真正面对任何错误,只是不起作用。这段代码是第一次尝试,我知道这是错误的。我所需要的只是将一个文本文件存储在一个具有1个键和2个值的关联数组中:-)