如果为空,PHP合并数组

Is there a nice way to merge two arrays in PHP.

My $defaults-array contains default values. If the $properties-array contains an empty string I want to use the value from the $defaults-array.

My code so far looks as following:

    $defaults = array( 
        'src' => site_url() . '/facebook_share.png',
        'alt' => 'Facebook',
        'title' => 'Share',
        'misc' => '',
        );


    $properties = array( 
        'src' => '',
        'alt' => '',
        'title' => 'Facebook Share',
        'text' => 'FB Text', //further properties
        );

$arr = array_merge( $defaults, $properties);
var_dump($arr);

Current result:

    $arr = array( 
        'src' => '',
        'alt' => '',
        'title' => 'Facebook Share',
        'text' => 'FB Text',
        'misc' => '',
        );

Desired result:

    $arr = array( 
        'src' => site_url() . '/facebook_share.png',
        'alt' => 'Facebook',
        'title' => 'Facebook Share',
        'text' => 'FB Text',
        'misc' => '',
        );

Hope someone can help.

3个回答



尝试:</ p>

  $ arr = array_merge($ defaults,array_filter($ properties)  )); 
</ code> </ pre>

请记住, array_filter </ code>将过滤掉空字符串''</ code>的元素, 0 </ code>, null </ code>, false </ code>。</ p>
</ div>

展开原文

原文

Try:

$arr = array_merge($defaults, array_filter($properties));

Keep in mind that array_filter will filter out elements that are empty string '', 0, null, false.

Try with this function

/**
  * @param {array} the properties array. transmitted by referance 
  * @param {array} the default array
  */
function getTheBest(&$properties, $defaults) {
    $temp = $properties;
    foreach ($properties as $key => $value) {
        if(empty($properties[$key]) && array_key_exists($key, $defaults) && !empty($defaults[$key]) ) {
            $properties[$key] = $defaults[$key];
        }
    }
}



这很好用:</ p>

 $ arr = array_merge($ defaults,array_filter($ properties)  ); 
</ pre>
</ div>

展开原文

原文

This works fine:

 $arr = array_merge($defaults, array_filter($properties));

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐