douli0531 2014-04-08 19:00
浏览 58

将文件中的数据读入关联数组

I have a file read.txt with records like this

pulp_fiction
Pulp Fiction
jurassic_park
Jurassic Park
inception
Inception

I want to read these content of the file to an associative array like this in quest.php

<?php
 $quest ["pulp_fiction"] = "Pulp Fiction";
 $quest ["jurassic_park"] = "Jurassic Park";
 $quest ["inception"] = "Inception";

this is the code that opens the file for writing in the quest.php I need help in the array part. thks

<?php
$myFile = "read.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
$assoc_array = array();
$my_array = explode("
", $theData);
foreach($my_array as $line)
{
    $tmp = explode("
", $line);
    $assoc_array[$tmp[0]] = $tmp[1];
}
fclose($fh);

// well the op wants the results to be in $quest
$quest = $assoc_array;
?>

I have this section of code saved as quest.php and am calling in quiz.php but when I try to match the image title with the actual title, nothing populates.

  • 写回答

3条回答 默认 最新

  • dswwuo1223 2014-04-08 19:06
    关注

    Probably a slicker way, but this was my first thought:

    $lines = file("read.txt", FILE_IGNORE_NEW_LINES);
    $pairs = array_chunk($lines, 2);
    
    foreach($pairs as $array) {
        $quest[$array[0]] = $array[1];
    }
    

    Needs some var and error checking.

    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程