<code>if(in_array($file_ext, $ext_arr['image'])) $file_path='uploads/image/'.$new_file_name; if(in_array($file_ext, $ext_arr['media'])) $file_path='uploads/media/'.$new_file_name; if(in_array($file_ext, $ext_arr['file'])) $file_path='uploads/file/'.$new_file_name; </code>
大家看看上面的代码如何精简一下。
<code>if(in_array($file_ext, $ext_arr['image'])) $file_path='uploads/image/'.$new_file_name; if(in_array($file_ext, $ext_arr['media'])) $file_path='uploads/media/'.$new_file_name; if(in_array($file_ext, $ext_arr['file'])) $file_path='uploads/file/'.$new_file_name; </code>
大家看看上面的代码如何精简一下。
把 $ext_arr
给取缔了,改成
<code class="lang-php">$types_of_extensions = array( 'jpg' => 'image', 'png' => 'image', 'gif' => 'image', 'rmvb' => 'media', 'mp3' => 'media', 'doc' => 'file', 'pptx' => 'file' /* ... and many more, whatever u want */ ); $file_path = 'uploads/' . $types_of_extensions[$file_ext] . '/' . $new_file_name; </code>
<code>foreach(array('image', 'media', 'file') as $type) foreach($ext_arr[$type] as $t) @$ext[$t] = $type; $file_path = "uploads/{$ext[$file_ext]}/$new_file_name"; </code>
只是讨论精简的话,这个成功精简三行的样子而且字数上也少很多,两行的样子比较难看我就不缩了~
精简减不了 流程上可优化
<code>if(in_array($file_ext, $ext_arr['image'])) $file_path='uploads/image/'.$new_file_name; elseif(in_array($file_ext, $ext_arr['media'])) $file_path='uploads/media/'.$new_file_name; elseif(in_array($file_ext, $ext_arr['file'])) $file_path='uploads/file/'.$new_file_name; </code>
<code class="lang-php">foreach (array('image', 'media', 'file') as $type) { if(in_array($file_ext, $ext_arr[$type])){ $file_path="uploads/$type/$new_file_name"; break; } } </code>
这代码高亮不支持高亮 PHP 里的字符串内插么……