Home > Backend Development > PHP Tutorial > php 代码优化

php 代码优化

WBOY
Release: 2016-06-06 20:22:46
Original
1151 people have browsed it

<code>   $data = [
        'field1' => isset($params['field1']) ? $params['field1'] : 0,
        'field2' => isset($params['field2']) ? $params['field2'] : 0,,
        'field3' => isset($params['field3']) ? $params['field3'] : 0,
        'field4' => isset($params['field4']) ? $params['field4'] : 0,
        'field5' => isset($params['field5']) ? $params['field5'] : 0,
        'field6' => isset($params['field6']) ? $params['field6'] : 0,
        'field7' => isset($params['field7']) ? $params['field7'] : 1,

    ];
    
    在往数据库中插入的时候,这种代码该如何优化</code>
Copy after login
Copy after login

回复内容:

<code>   $data = [
        'field1' => isset($params['field1']) ? $params['field1'] : 0,
        'field2' => isset($params['field2']) ? $params['field2'] : 0,,
        'field3' => isset($params['field3']) ? $params['field3'] : 0,
        'field4' => isset($params['field4']) ? $params['field4'] : 0,
        'field5' => isset($params['field5']) ? $params['field5'] : 0,
        'field6' => isset($params['field6']) ? $params['field6'] : 0,
        'field7' => isset($params['field7']) ? $params['field7'] : 1,

    ];
    
    在往数据库中插入的时候,这种代码该如何优化</code>
Copy after login
Copy after login

<code> $data=array_map(function($v,$k){

   $default=0;
   if($k=='field7') $default=1;
   #return $v??$default; //php7
   return isset($v) ? $v : $default;

 },$data,array_keys($data));
</code>
Copy after login

<code class="php">$fields = array('field1'=>0, 'field2'=>'default_value');
$data = array();
foreach ($fields as $k=>$v) {
    $data[$k] = isset($params[$k]) ? $params[$k] : $v;
}</code>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template