我试图根据laravel中的扩展对我的数据库进行排序,所以我尝试使用pathinfo对其进行排序,并将其与循环混合,但是由于某种原因,变量$ext_name没有输出文件的真正扩展名。
这是我的代码:
$i = 0;
$pdf_file = [];
$docx_file = [];
$pdf = 0;
$docx = 0;
foreach($files as $i => $the_file){
$path_name[$i] = $the_file["file_path"];
$ext_name[$i] = pathinfo($path_name[$i],PATHINFO_EXTENSION);
if($ext_name[$i]="pdf"){
$pdf_file[$pdf]= $the_file["name"];
}
elseif($ext_name[$i]="docx"){
$docx_file[$docx]= $the_file["name"];
}
++$i;
++$pdf;
++$docx;
}$path_name和$ext_name的dd结果:
$path_name
array:5 [▼
0 => ".........../storage/app/file_processing/blablabla.pdf"
1 => ".........../storage/app/file_processing/blablabla.docx"
2 => ".........../storage/app/file_processing/blablabla.pdf"
3 => ".........../storage/app/file_processing/blablabla.pdf"
4 => ".........../storage/app/file_processing/blablabla.docx"
]$ext_name
array:5 [▼
0 => "pdf"
1 => "pdf"
2 => "pdf"
3 => "pdf"
4 => "pdf"
]我不知道$ext_name是如何输出相同的扩展的,我到底在哪里做错了什么?
发布于 2021-12-28 18:05:54
您可以稍微清理一下代码。
$pdf_file = [];
$docx_file = [];
$ext_name = [];
foreach($files as $key => $file){
$ext_name[$key] = pathinfo($file["file_path"],PATHINFO_EXTENSION);
if($ext_name[$key] === "pdf"){
$pdf_file[$key]= $file["name"];
} elseif ($ext_name[$key] === "docx"){
$docx_file[$key]= $file["name"];
}
}
dd($pdf_file,$docx_file,$ext_name);您应该使用==或===而不是=。
还有为什么会发生这种事?因为您将pdf分配给ext_name[$i],所以ext_name[$i]的每次迭代都会编写pdf扩展。
=是赋值运算符,== ond ===是相等运算符。
发布于 2021-12-28 18:04:36
试一试如下:
if ($ext_name[$i] === "pdf") {或
if ($ext_name[$i] == "pdf") {但不要这样做:
if ($ext_name[$i] = "pdf") {注意到,单个等号总是只设置变量,即使它是用if -语句编写的。
你的另一行也是一样:
($ext_name$i=“docx”){
https://stackoverflow.com/questions/70510751
复制相似问题