在另一个用户的帮助下,我得到了我想要的二维数组。我得到的每个ID ($talente)都会从CSV中保存一行。对数组来说很有魅力。但是输出让我很困惑。
这是我使用的CSV:
Schild,1,Licht,1w10,-
Schutz,1,Licht,1w10,-
Licht,4,Licht,1w10,-
Genesung,1,Licht,-,-
Aufopfern,1,Licht,-,-
脚本:
<?php
$talente = $_GET['talente'];
$myFile = fopen("talente.csv", "r");
$csv = [];
while ($data = fgetcsv($myFile, 1000, ",")) {
$csv[] = $data;
}
fclose($myFile);
$talentline = array_filter($csv, function($i) use ($talente) {
return in_array($i, $talente);
}, ARRAY_FILTER_USE_KEY);
print_r(array_values($talentline));
echo $talentline[1][0];
echo $talentline[2][0]; //line 21.
echo $talentline[3][0];
?>
print_r(元素(talentline美元));为id的1 &3.
[0] => Array (
[0] => Schutz
[1] => 1
[2] => Licht
[3] => 1w10
[4] => -
)
[1] => Array (
[0] => Genesung
[1] => 1
[2] => Licht
[3] => -
[4] => -
)
最后的三个回声给了我这个:
有两个问题我不能解决。第一个是,打印的行是在我期望的行之后的一行。所以我希望不是"Schutz"而是"Schild"。舒兹注意:未定义的偏移量:2在C:'xampp'htdocs'DvC Generator'php'test.php第21行Genesung
我遇到的更大的问题是,脚本保存了与ID相等的数组位置的行。这不是我需要的,因为它也保存空数组元素。当id 1和3被发送时,我期望的结果是Schild at array[0]和light at array[1]。
我希望我能解释得足够清楚。
数组值从0
开始计数
0是第一,1是第二。
你的"未定义的偏移"的问题是由于你只是"保持"在$_GET['talente']
输入数组中找到的数组值。如果您将此值更改为2
,那么您将获得1和3的未定义偏移通知,等等。
你的第一个问题是数组从[0]
开始,所以如果你在新的talentline
数组中有两个值,那么第一个是键[0]
,第二个值是键[1]
。等。
你的第二个问题是相关的,因为你正在比较匿名函数中的键值,你正在寻找第一个值(数组键[0]
)通过请求$_GET
数组给出的值1
。这就是为什么它会给你意想不到的(但正确的)结果。
解决方案:
第二个问题(这是一个编码错误):
您需要通过将键值增加+1或将输入参考值减少-1来调整键值,以使输入与给定的CSV值对齐:
return in_array($i, $talente--); //reduces the input comparison value by 1,
//so that the first value ("1") is treated as key "0".
其次,要修复在脚本后面引用未设置的数组引用时收到的通知:
print isset($talentline[2][0]) ? $talentline[2][0]; : "";
// shorthand PHP stating that if value is set then print it,
// else don't print anything.
代码我用来达到这个答案(PHP 5.6.2)。显然,调整了,因为我没有你的CSV文件要导入,等等。
<?php
$talente = array(0=>1,1=>3);
$csv[] = array(0=>"Schild", 1=>1, 2=>"Licht", 3=>"1w10", 4=>"-");
$csv[] = array(0=>"Schutz", 1=>1, 2=>"Licht", 3=>"1w10", 4=>"-");
$csv[] = array(0=>"Licht", 1=>4, 2=>"Licht", 3=>"1w10", 4=>"-");
$csv[] = array(0=>"Genesung",1=>1,2=>"Licht",3=>"-",4=>"-");
$csv[] = array(0=>"Aufopfern",1=>1,2=>"Licht",3=>"-",4=>"-");
$talentline = array_filter($csv, function($i) use ($talente) {
return in_array($i, $talente--);
}, ARRAY_FILTER_USE_KEY);
$talentline = array_filter($talentline);
print_r(array_values($talentline));
print isset($talentline[1][0]) ? $talentline[1][0]; : "";
print isset($talentline[2][0]) ? $talentline[2][0]; : "";
print isset($talentline[3][0]) ? $talentline[3][0]; : "";