dousi1097 2014-06-12 11:05
浏览 45
已采纳

循环通过未知的数组键/测试丢失的键

I am trying to set up a structure where an associative array holds key/value data for a template of mine.

I want to be able to apply default data, but the below code has some obvious problems. First of all, it's a hassle writing that repetitive stuff. Second - the test for null doesn't work if the key isn't defined at all, then you just get an error saying that key 'background_color' is not defined.

How would I best go about structuring something like this?

//Defaults for this template
$default = array();
$default['background_color'] = '#ffffff';
$default['background_image'] = '';
$default['background_opacity'] = '1.0';
$default['background_repeat'] = '';
$default['background_position-horizontal'] = 'left';
$default['background_position-vertical'] = 'top';
$default['background_size'] = '';

if($data['background_color'] == null) { $data['background_color'] = $default['background_color']; }
if($data['background_image'] == null) { $data['background_image'] = $default['background_image']; }
if($data['background_opacity'] == null) { $data['background_opacity'] = $default['background_opacity']; }
if($data['background_repeat'] == null) { $data['background_repeat'] = $default['background_repeat']; }
if($data['background_position-horizontal'] == null) { $data['background_position-horizontal'] = $default['background_position-horizontal']; }
if($data['background_position-vertical'] == null) { $data['background_position-vertical'] = $default['background_position-vertical']; }
if($data['background_size'] == null) { $data['background_size'] = $default['background_size']; }
  • 写回答

3条回答 默认 最新

  • duanfen7676 2014-06-12 11:16
    关注

    The way I always do a 'default' scenario is:

    $data = (array)$data + (array)$default;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?