PHP->文本文件内容到数组



我正在尝试转换此文本文件:

mammals|A living thing that gives birth to their young.
mammals|A living thing that produce milk for their young.
mammals|A living thing that can grow hair or fur.
warm-blooded|The ability to produce own body heat
lungs|Mammals use this to breathe.
lungs|Mammals breathe with __________.
lungs|__________ helps mammals to breathe.
birth|Mammals give __________ to their young.
milk|Mammals produce this to feed their young.
hair|Some mammals, especially human, grow __________ on their skin.
fur|Some mammals, such as bears, grow __________ on their skin.

进入PHP数组为:

array(
mammals=>A living thing that gives birth to their young.
mammals=>A living thing that produce milk for their young.
mammals=>A living thing that can grow hair or fur.
warm-blooded=>The ability to produce own body heat
lungs=>Mammals use this to breathe.
lungs=>Mammals breathe with __________.
lungs=>__________ helps mammals to breathe.
birth=>Mammals give __________ to their young.
milk=>Mammals produce this to feed their young.
hair=>Some mammals, especially human, grow __________ on their skin.
fur=>Some mammals, such as bears, grow __________ on their skin.
)

我试过了:

$array_mammals = explode("n", file_get_contents('cw_mammals.txt'));
foreach ($array_mammals as $key => $value) {
$list_mammals[] = explode('|', $value);
}
print_r($list_mammals);

我得到了:

Array ( 
[0] => Array ( [0] => mammals [1] => A living thing that gives nirth to their young. ) 
[1] => Array ( [0] => mammals [1] => A living thing that produce milk for their young. ) 
[2] => Array ( [0] => mammals [1] => A living thing that can grow hair or fur. ) 
[3] => Array ( [0] => warm-blooded [1] => The ability to produce own body heat ) 
[4] => Array ( [0] => lungs [1] => Mammals use this to breathe. ) 
[5] => Array ( [0] => lungs [1] => Mammals beathe with __________. ) 
[6] => Array ( [0] => lungs [1] => __________ helps mammals to breathe. ) 
[7] => Array ( [0] => birth [1] => Mammals give __________ to their young. ) 
[8] => Array ( [0] => milk [1] => Mammals produce this to feed their young. ) 
[9] => Array ( [0] => hair [1] => Some mammals, especially human, grow __________ on their skin. ) 
[10] => Array ( [0] => fur [1] => Some mammals, such as bears, grow __________ on their skin. ) ) 

我需要每一行的第一个单词的键,但我似乎无法正确处理方法。任何建议都将不胜感激。

你不能像@esqew提到的那样拥有一个你想要的数组。数组应该始终具有唯一的键。但是,如果这有帮助的话,你可以在你现有的问题上尝试一下。

<?php
$array_mammals = explode("n", file_get_contents('cw_mammals.txt'));
foreach ($array_mammals as $key => $value) {
$list_mammals[] = explode('|', $value);
}
foreach ($list_mammals as $list) {
echo $list[0]. "-". $list[1];
}

?>

因为在一个数组中不能有相同的键,但您可以制作一个特定键的数组,以为您的问题保留相同类型的值。

$array_mammals = explode("n", file_get_contents('cw_mammals.txt'));
$mammals = [];
foreach ($array_mammals as $value) {
$key_vallue = explode('|', $value);
$mammals[ $key_vallue[0] ] [] = $key_vallue[1]; 
}
var_dump($mammals);

最新更新