如何拆分PHP数组,以便可以访问每个值

时间:2015-01-09 14:35:10

标签: php arrays

我正在使用PHP阅读文件:

$file = file('myfile.txt');

这会将行中的每一行存储为数组中的单独值。

myfile.txt的

123-12333 : Example
456-45666 : MyWorld

结果是:

Array( [0] => 123-12333 : Example [1] => 456-45666 : MyWorld)

我需要拆分每个索引值,以便我的结果最终会像这样:

Array([0] => 123-12333 [1] => : [2] => Example [3] => 456-45666 [4] => : [5] => MyWorld)

我需要拆分数组,以便可以独立访问每个值。

array_chunk似乎不起作用,array_slice也没有帮助。有什么建议??

我尝试过的事情是:

 print_r(array_chunk($fileContents,2));

结果:

Array ( [0] => Array ( [0] => 123-12333 : Duan Uys [1] => 345-34555 : Dennis Taylor ) [1] => Array ( [0] => 555-55555 : Darwin Award ) )

4 个答案:

答案 0 :(得分:1)

试试这个:

$file     = file('myfile.txt');
$splitted = array();
foreach ($file as $line) {
    $splitted = array_merge($splitted, explode(' ', $line));
}
//now $splitted will have the format you need

答案 1 :(得分:0)

myfile.txt的:

123-12333 : Example
456-45666 : MyWorld

PHP:

$file = 'myfile.txt';
$content = file_get_contents($file);
$lines = explode("\n", $content);
$returnArray = array();
foreach ($lines as $line) {
    $returnArray[] = explode(' ', $line);
}

print_r($returnArray);

正如您在评论中提到的,您需要第一部分。为此,请更改:

$returnArray[] = explode(' ', $line);    

到:

$returnArray[] = current(explode(' ', $line));

答案 2 :(得分:0)

您可以将每个部分作为字符串传递给变量,然后使用":"稀释,然后把它放在这样的数组:

$output=array();
foreach ($input as $key=>$value){
    $output[$key][]=substr($value,0,strpos($value,' : '));
    $output[$key][]=substr($value,strpos($value,' : ')+3,strlen($value));
}

答案 3 :(得分:0)

一些fscanf动作怎么样......这几乎是它的预期用途:

$handle = fopen("myfile.txt", "r");
$lines = array();

while ($line = fscanf($handle, "%s : %s\n")) {
    array_merge($lines, $line);   
}

fclose($handle);

这将省略冒号,但我不认为这有用,因为你说:

  

我需要隔离123-12333,这就是为什么我需要将它们全部分开。

这与使用file然后循环和修改内容的其他方法非常相似,但它还具有逐行读取文件的额外好处,因此整个内容首先不在内存中。如果您的文件非常小,这可能无关紧要,但如果此文件很大或随着时间的推移会变大,这可能会很重要。另外,如果您只想要数字,那么您可以这样做:

$handle = fopen("myfile.txt", "r");
$numbers = array();

while ($line = fscanf($handle, "%s : %s\n")) {
   $numbers[] = $line[0]; 
}

fclose($handle);