我有图像中的结构文件。我想从那里提取数据到数组:
function get_data($file, $number)
{
if(!$fp = fopen ($file, 'rb')) return 0;
$fsize = filesize($file);
if(!$data = fread ($fp, $fsize)) return 0;
$data_format=
'@100/'.
'smember_id/'.
'cmember_name_length/'.
'a' . $member_name_length . 'member_name/'.
'C100other_data/';
$data = unpack ($data_format, $data);
fclose($file);
return $data;
}
如何从文件中获取$ member_name_length?我想创建一个函数,如果用户输入$ number,它将返回一个$ number(th)数据的数组。
谢谢。
答案 0 :(得分:1)
由于你有一个可变长度的数据块,你只能按顺序读取它们,所以为了读取第n个块,你需要读取所有n个第一个块:
function readDataBlock($f) {
$data = unpack('nmember_id', fread ($f, 2)); // I assume member_id is n, not s
if ($data['member_id'] == 0xFFFF) {
throw new \Exception('End of file');
}
$data = array_merge($data, unpack('Cmember_name_length', fread ($f, 1))); //again, it must be C, not c, as I can't imagine negative length.
$data = array_merge($data, unpack('a*member_name', fread ($f, $data['member_name_length']))); // be sure you understand how a differs from A
return array_merge($data, unpack('C100other_data', fread ($f, 100))); // are you sure C100 is what you want here?
}
function get_data($file, $number)
{
if(!$fp = fopen ($file, 'rb')) return 0;
fread ($fp, 100); //skip header
for($n = 0; $n <= $number; $n++) {
$data = readDataBlock($fp); // read single member
}
fclose($fp);
return $data; //return the n-th member
}
如果文件足够小以适应内存,最好一次读取它并从内存中返回第n个成员:
$data = [];
while(true) {
try {
$data[] = readDataBlock($fp);
} catch(\Exception $e) {
break;
}
}
function get_data(&$data, $number)
{
return $data[$number];
}