douxian0279 2017-08-21 18:58
浏览 49
已采纳

将文件数据文本传输到PHP和搜索数据中的关联数组

I'm a beginner in PHP. I have a text file like this:

Name-Id-Number
Abid-01-80
Sakib-02-76

I can take the data as an array but unable to take it as an associative array. I want to do the following things:

  • Take the data as an associative array in PHP.
  • Search Number using ID.
  • Find out the total of Numbers
  • 写回答

1条回答 默认 最新

  • drmgg4411 2017-08-21 20:07
    关注

    I believe I understand what you want, and it's fairly simple. First you need to read the file into a php array. That can be done with something like this:

    $filedata = file($filename, FILE_IGNORE_NEW_LINES);

    Now build your desired array using a foreach() loop, explode and standard array assignment. Your search requirement is unclear, but in this example, I make the associated array element into an array that is also an associative array with keys for 'id' and 'num'.

    As you create the new array, you can compute your sum, as demonstrated.

    <?php
    
    $filedata = array('Abid-01-80', 'Sakib-02-76');
    
    $lineArray = array();
    $numTotal = 0;
    
    foreach ($filedata as $line) {
        $values = explode('-', $line);
        $numTotal += $values[2];
        $lineArray[$values[0]] = array('id' => $values[1], 'num' => $values[2]);
    }
    
    echo "Total: $numTotal
    
    ";
    var_dump($lineArray);
    

    You can see this code demonstrated here

    Updated response:

    Keep in mind that notices are not errors. They are notifiying you that your code could be cleaner, but are typically suppressed in production.

    The undefined variable notices are coming because you are using:

    $var += $var without having initialized $var previously. Note that you were inconsistent in this practice. For example you initialized $numTotal, so you didn't get a notice when you used the same approach to increment it.

    Simply add just below $numTotal = 0:

    $count = 0;
    $countEighty = 0;
    

    Your other notices are occurring most likely due to a blank line or string in your input that does not follow the pattern expected. When explode is executed it is not returning an array with 3 elements, so when you try and reference $values = explode('-', $line); you need to make sure that $line is not an empty string before you process it. You could also add a sanity check like:

    enter code hereif (count($values) === 3) { // It's ok to process

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵