【问题标题】:Better way to rewrite an if else sequence重写 if else 序列的更好方法
【发布时间】:2015-11-09 04:02:30
【问题描述】:

我想问写这个if else语句序列有什么更好的:

$dir = base_url()."assets/produits/";
  $img_src = $dir."none.png";

  if (!empty($row->nShape)) {
      $nom = $row->nShape;

  if (file_exists($dir.$nom.".JPEG")) {
      $img_src = $dir.$nom.".JPEG";
  }
  else
  if (file_exists($dir.$nom.".jpg")) {
      $img_src = $dir.$nom.".jpg";
  }
  else
  if (file_exists($dir.$nom.".jpeg")) {
      $img_src = $dir.$nom.".jpeg";
  }
  }

完整的 MVC 模式

实施后:https://stackoverflow.com/a/32034937/5203821回答

查看文件

<div class="container">
    <?=$message?>
    <?php
    foreach ($rows as $row) {
    $dir = base_url()."assets/produits/";
    $img_src = $dir."none.png";

    if (!empty($row->nShape)) {
            $nom = $row->nShape;

    $type = array(".JPEG", ".jpg", ".jpeg");

    foreach ($type as $ext) {
        if (file_exists($dir.$nom.$ext)) {
            $img_src = $dir.$nom.$ext;
            break;
        }
    }
}

    ?>

    <div class="list-group">
        <a class="list-group-item col-md-4" target="_blanc" href="<?=site_url()?>/produits/detail/<?=$row->nProduct?>" title="<?=$row->sSort?>"><b><img src="<?=$img_src?>" alt="<?=$row->nShape?>" class="img-rounded product"><?=$row->sSearch?></b></a>
    </div>
    <?php
    }
     ?>
    <div class="spacer"></div>
</div>

模型文件

<?php

defined('BASEPATH') OR exit('No direct script access allowed');
    class Product_model extends CI_Model{

      function getProduct($product_id){
        $this->db->from('tequivalent')
                  ->where('nReference',$product_id)
                  ->join('tProduct','tProduct.nProduct=tequivalent.nProduct1');

                $query = $this->db->get();
                $ret['rows'] = $query->result();
                $ret['number'] = $query->num_rows();
                $ret['id'] = $product_id;

                return $ret;
      }
    }

控制器文件

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Produits extends CI_Controller {


    function index($product_id='')
    {

        if($product_id==NULL){
            redirect();
        }
        $this->load->model('Product_model');
        $query = $this->Product_model->getProduct($product_id = $this->uri->segment(3, 0));

        if($query['number']>0){
            $results['message']="<h2>Clique sur une Référence pour Plus de Detail</h2>";
            $results['number'] = $query['number'];
            $results['rows'] = $query['rows'];
        }else{
            $results['message'] = "<p>Oops! Y'a Aucun Résultat pour cette recherche</p>";
            $results['message'] .= "<a class='btn btn-lg btn-danger' href=".site_url().">Acceuil</a>";
            $results['number'] = $query['number'];
            $results['rows'] = $query['rows'];
            $results['id'] = $query['id'];
        }

        $this->load->view('constants/header');
        $this->load->view('produits',$results);
        $this->load->view('constants/footer');

}
}

上面的代码如果是完整的 MVC 模式,因为我使用的是 Codeigniter 感谢大家的贡献

【问题讨论】:

  • 如果您不能标准化文件的保存方式,我可能会glob() 目录并对结果数组进行不区分大小写的匹配。

标签: php


【解决方案1】:

您可能可以使用 foreach 循环合并三个 if 语句:

dir = base_url()."assets/produits/";
    $img_src = $dir."none.png";

    if (!empty($row->nShape)) {
            $nom = $row->nShape;

    $type = array(".JPEG", ".jpg", ".jpeg");

    foreach ($type as $ext) {
        if (file_exists($dir.$nom.$ext)) {
            $img_src = $dir.$nom.$ext;
            break;
        }
    }
}

通过向数组添加扩展可以显着减少多余的 if 语句。

【讨论】:

  • 它显示无占位符,并且图像文件存在
  • $img_src = $dir.$nom.$ext; 之后添加echo $img_src;,看看是否有任何输出。
  • 它显示了 none.png 占位符我已经添加了 MVC 模式检查一下
  • 我已经添加了完整的代码,你可以查看我做了什么
  • 尝试添加我提到的回声线(在$img_src = $dir.$nom.$ext;break 之间)。
【解决方案2】:

你可以使用这个取自here的函数,忽略大小写:

function fileExists($fileName, $caseSensitive = true) {

    if(file_exists($fileName)) {
        return $fileName;
    }
    if($caseSensitive) return false;

    // Handle case insensitive requests            
    $directoryName = dirname($fileName);
    $fileArray = glob($directoryName . '/*', GLOB_NOSORT);
    $fileNameLowerCase = strtolower($fileName);
    foreach($fileArray as $file) {
        if(strtolower($file) == $fileNameLowerCase) {
            return $file;
        }
    }
    return false;
}

现在你可以迭代了:

$allowedExtensions = ["jpeg","jpg"];

foreach($allowedExtensions as $ext){
     if(fileExists("youfFileName.$ext"),false){
         //do your code..
     }
}

【讨论】:

  • 但是我可以在哪里确定指定的目录?
  • 只需发送完整路径“full/path/to/file/file.jpg”; fileExists 知道如何使用 dirname($fileName); 在文件的文件夹中搜索
  • 但我不能在 foreach 循环中使用函数,请在问题中查看上述内容
  • 为什么不能?我不明白原因
  • Cannot redeclare fileExists() (previously declared in C:\xampp\htdocs\dedax_new\application\views\produits.php:9)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2012-11-26
  • 1970-01-01
相关资源
最近更新 更多