如何使php回显数组的子部分

时间:2015-05-11 01:11:56

标签: php

的index.php

<?php
$filename = "101.txt";

$file = file($filename, FILE_IGNORE_NEW_LINES);

print_r($file);
echo "</br>".$file[1];
?>

101.txt

1, 100, 001.txt
101, 200, 002.txt
201, 300, 003.txt
301, 400, 004.txt

index.php的结果

Array ( [0] => 1, 100, 001.txt [1] => 101, 200, 002.txt [2] => 201, 300, 003.txt [3] => 301, 400, 004.txt )
101, 200, 002.txt

我想要的是像

$file[1][1];

哪个会输出“200”而不是完整的字符串。 有谁知道这样做的方法?

2 个答案:

答案 0 :(得分:1)

array_walk 可以遍历数组并运行回调。例如,一个用逗号分解值的函数。下面是使用array_walk的匿名函数的示例。

array_walk($file, function(&$value, $key) {
   $value = explode(', ', $value);
});

转换$file

Array
(
    [0] => 1, 100, 001.txt
    [1] => 101, 200, 002.txt
    [2] => 201, 300, 003.txt
    [3] => 301, 400, 004.txt
)

到多维$file

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 100
            [2] => 001.txt
        )

    [1] => Array
        (
            [0] => 101
            [1] => 200
            [2] => 002.txt
        )

    [2] => Array
        (
            [0] => 201
            [1] => 300
            [2] => 003.txt
        )

    [3] => Array
        (
            [0] => 301
            [1] => 400
            [2] => 004.txt
        )

)

您可以访问&#39; 200&#39;在$file[1][1]

这是有效的,因为 $ value (每个数组元素的值)是一个引用(注意&$value)。所以你可以修改它,它会更新原始数组。

答案 1 :(得分:0)

请改为尝试:

$filename = "101.txt";
$file = file($filename, FILE_IGNORE_NEW_LINES);
$value = explode(', ', $file[1]); //explode the 2nd array
echo $value[1]; //echo the 2nd value of 2nd array
//200

参考文献:

http://php.net/explode