duanben1909 2016-09-23 20:10
浏览 47
已采纳

如何创建一个矩阵,以便我可以从数组中访问每个数字,如$ array [$ key]

I am trying to create a multi-dimensional array from a text file so I can access each number. For example the first 7 would be $triangle[0][0] and the first 5 would be $triangle[0][1]. The code I've written so far is

<?php
$triangles = explode("
", file_get_contents('18.txt'));
var_dump($triangles);
?>

This produced the following output. What do I need to change here? Thanks

array (size=15)
 0 => string '75' (length=3)
 1 => string '95 64' (length=6)
 2 => string '17 47 82' (length=9)
 3 => string '18 35 87 10' (length=12)
 4 => string '20 04 82 47 65' (length=15)
 5 => string '19 01 23 75 03 34' (length=18)
 6 => string '88 02 77 73 07 63 67' (length=21)
 7 => string '99 65 04 28 06 16 70 92' (length=24)
 8 => string '41 41 26 56 83 40 80 70 33' (length=27)
 9 => string '41 48 72 33 47 32 37 16 94 29' (length=30)
10 => string '53 71 44 65 25 43 91 52 97 51 14' (length=33)
11 => string '70 11 33 28 77 73 17 78 39 68 17 57' (length=36)
12 => string '91 71 52 38 17 14 91 43 58 50 27 29 48' (length=39)
13 => string '63 66 04 68 89 53 67 30 73 16 69 87 40 31' (length=42)
14 => string '04 62 98 27 23 09 70 98 73 93 38 53 60 04 23' (length=44)
  • 写回答

1条回答 默认 最新

  • douhoulei4706 2016-09-23 20:50
    关注

    You can use file to get the contents of the file into an array where each array element is a line from the file, then map str_split over that array to separate each line into individual characters.

    $triangles = array_map('str_split', file('18.txt',  FILE_IGNORE_NEW_LINES ));
    
    echo $triangles[0][0];    // outputs 7
    echo $triangles[0][1];    // outputs 5
    

    If you don't want the spaces, you can use str_replace to remove them before splitting the line into individual characters.

    $triangles = array_map(function($line) {
        return str_split(str_replace(' ', '', $line));
    }, file('18.txt',  FILE_IGNORE_NEW_LINES ));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用