首先项目里有这样一大段代码:

if($zhenghao=='PD332-2000'){$dym1s='008753';}
elseif($zhenghao=='PD341-2000'){$dym1s='008752';}
elseif($zhenghao=='PD326-2000'){$dym1s='008751';}
elseif($zhenghao=='PD345-2000'){$dym1s='008750';}
elseif($zhenghao=='PD328-2000'){$dym1s='008749';}
elseif($zhenghao=='PD343-2000'){$dym1s='008748';}
...//中间省略若干行
else{$dym1s='';}

早期以为数据不再更新,就以if低效率的方式运行了,然而现在发现数据要更新。
1.这么多行数据写if语句也麻烦(早期是用excel批量做的代码然后复制粘贴文本)
2.多个项目多个文件都用到这一大段if代码
所以必须要换更简单的方式了,后期再更新数据也方便。
思路:多个文件调用同一文件的内容,只更新一个文件内容即可。

笔记1

  1. PHP调用其他文件中的类
    首先在一个tool.php文件中声明一个类:
<?php
  class tool {

  function say(){
  $result="Hello,World";
  return $result;
  }

}

在另一文件main.php调用上面的类中的方法:

<?php
  require_once 'tool.php';
  $tool=new tool();
  $content=$tool->say();
  echo $content;
?>
  1. PHP调用其他文件中的代码
    文件1.php
<?php
function say($zhenghao){
if($zhenghao=='PD332-2000'){$dym1s='008753';}
elseif($zhenghao=='PD341-2000'){$dym1s='008752';}
elseif($zhenghao=='PD326-2000'){$dym1s='008751';}
elseif($zhenghao=='PD345-2000'){$dym1s='008750';}
elseif($zhenghao=='PD328-2000'){$dym1s='008749';}
else{$dym1s='';}
return $dym1s;
}
?>

文件2.php

<?php
require_once '1.php';
$zhenghao = 'PD328-2000';
$dym1s = say($zhenghao);
echo $dym1s;
?>

这样只需更新1.php即可,然而大量if代码搞起来还是嫌麻烦,继续改进。

笔记2

php获取excel表格中数据的小方法
现在有一个product.xls的表格文件,要求取出其中数据
数据如下:

商品名 价格
iphone4s 4199
note2 3999
小米2 1999
iphone5 4899

1,将product.xls另存为product.csv文件
2,用fgetcsv函数取出其中的数据放到一个数组中(fgetcsv --- 从文件指针中读入一行并解析 CSV 字段)

代码如下:

<?php

$file=fopen('./product.csv','rb');
$data=array();//fgetcsv --- 从文件指针中读入一行并解析 CSV 字段
while($line=fgetcsv($file)){//一直取到文件结束,此事返回false
  $data[]=$line;

}
print_r($data);

/*
Array
(
    [0] => Array
        (
            [0] => 商品名
            [1] => 价格
        )

    [1] => Array
        (
            [0] => iphone4s
            [1] => 4199
        )

    [2] => Array
        (
            [0] => note2
            [1] => 3999
        )

    [3] => Array
        (
            [0] => 小米2
            [1] => 1999
        )

    [4] => Array
        (
            [0] => iphone5
            [1] => 4899
        )

    [5] =>
)
*/

?>

改进为:

<?php

$file=fopen('./product.csv','rb');
$data=array();//fgetcsv — 从文件指针中读入一行并解析 CSV 字段
while($line=fgetcsv($file)){//一直取到文件结束,此事返回false
$data[]=$line;
}
$post_meta_key = $zhenghao;

foreach ($data as $value) {
  if (in_array($post_meta_key, $value)) {
      $dym1s=$value[2]
  }
}

只需更新product.csv即可。
$file=fopen('./product.csv','rb');
product.csv在当前目录下,因为若干个调用product.csv数据的文件不在同一目录,所以改为product.csv放在网站根目录。
wordpress下调用根目录:

$wwwurl=home_url();
$file=fopen("$wwwurl/product.csv",'rb');

其它网站项目调用此数据的话用到PHP fopen() 函数的使用方法之一:

$file = fopen("http://www.example.com/product.csv","rb");

最后修改:2020 年 08 月 06 日
收藏不易,如果感觉对你有用,请随意打赏支持下