if (isset($views[0]['art_classid'])) { $views[0]['class_link'] = "/zx-" . $views[0]['art_classid'] . "/"; } elseif (isset($views[0]['art_typeid'])) { $views[0]['class_link'] = "/type-" . $views[0]['art_typeid'] . "/"; } if (isset($views[0]['art_picurl'])) { $views[0]['art_picurl'] = $views[0]['art_picurl'] ? $views[0]['art_picurl'] : "http://images.9191zx.com/d/art_nopic.jpg"; } 把这段代码优化到极致
时间: 2023-05-22 17:01:35 浏览: 109
作为一个 AI,我可以给出以下建议来优化这段代码:
1. 使用三元运算符来简化 if-else 语句,例如:$views[0]['class_link'] = isset($views[0]['art_classid']) ? "/zx-" . $views[0]['art_classid'] . "/" : "/type-" . $views[0]['art_typeid'] . "/";
2. 使用逻辑或运算符来简化条件语句,例如:$views[0]['art_picurl'] = $views[0]['art_picurl'] || "http://images.9191zx.com/d/art_nopic.jpg";
3. 避免重复的代码,例如:将 $views[0] 提取为一个变量,以便在代码中多次使用。
综上所述,优化后的代码如下:
$art = $views[0];
$art['class_link'] = isset($art['art_classid']) ? "/zx-" . $art['art_classid'] . "/" : "/type-" . $art['art_typeid'] . "/";
$art['art_picurl'] = $art['art_picurl'] || "http://images.9191zx.com/d/art_nopic.jpg";
相关问题
if (isset($views[0]['art_classid'])) { $views[0]['class_link'] = "/zx-" . $views[0]['art_classid'] . "/"; } elseif (isset($views[0]['art_typeid'])) { $views[0]['class_link'] = "/type-" . $views[0]['art_typeid'] . "/"; } if (isset($views[0]['art_picurl'])) { $views[0]['art_picurl'] = $views[0]['art_picurl'] ? $views[0]['art_picurl'] : "http://images.9191zx.com/d/art_nopic.jpg"; } 优化下这段代码
为了优化这段代码,我们可以使用三元运算符来简化 if-else 语句的写法,同时可以使用 isset() 函数的返回值来避免重复调用该函数。下面是优化后的代码:
$views = isset($views[0]) ? $views[0] : array();
$views['class_link'] = isset($views['art_classid']) ? "/zx-" . $views['art_classid'] . "/" : (isset($views['art_typeid']) ? "/type-" . $views['art_typeid'] . "/" : "");
$views['art_picurl'] = isset($views['art_picurl']) && $views['art_picurl'] ? $views['art_picurl'] : "http://images.9191zx.com/d/art_nopic.jpg";
这样,我们就可以更加简洁地实现相同的功能。
阅读全文