【问题标题】:php loop foreach wrong output [duplicate]php循环foreach错误的输出[重复]
【发布时间】:2022-01-27 07:40:38
【问题描述】:

我试图根据 laravel 中的扩展名对我的数据库进行排序,所以我尝试使用 php 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 是如何输出相同的扩展名的,我到底哪里做错了?

【问题讨论】:

  • 您正在分配值而不是在您的 if 语句中进行比较
  • 所有的平等都是平等的。一些平等更平等。

标签: php laravel loops


【解决方案1】:

你可以稍微清理一下你的代码。

$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扩展。

= 是赋值运算符,== 和 === 是相等运算符

【讨论】:

  • 非常感谢您的努力,不仅修复并解释了错误的原因,还整理了我的代码,谢谢!
【解决方案2】:

尝试类似:

if ($ext_name[$i] === "pdf") {

或

if ($ext_name[$i] == "pdf") {

但不要这样做:

if ($ext_name[$i] = "pdf") {

注意单个等号总是只设置变量,即使它是用 if 语句编写的。

你的另一行也一样:

elseif($ext_name[$i]="docx"){

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 2018-05-30
    • 2015-09-21
    • 2023-03-17
    • 1970-01-01
    • 2018-12-11
    • 2013-12-18
    相关资源
    最近更新 更多