开发者

Get value of key when building array

I have an array that looks like this:

$widgets = array(
'ka' => array(
    'name'       => 'Kool-Aid',
    'active'     => true,
    'priority'   => 10,
    'primacy'    => 30,开发者_开发百科
    'controller' => 'KoolAid'.$widgets['ka']['settings']['ka_type'].'Widget',
    'settings'   => array(
        'ka_type'   => 'BBQ',
    ),
),
);

If you notice on the row 'controller' I want to put the value of $widgets['ka']['settings']['ka_type'] into the value.

Is there anyway that I can reference the value of a key in an array that I'm currently building?


You can't reference value before it exists. Assign value to temporary variable and then use it in both places.

$kaType = 'BBQ';
$widgets = array(
'ka' => array(
    'name'       => 'Kool-Aid',
    'active'     => true,
    'priority'   => 10,
    'primacy'    => 30,
    'controller' => 'KoolAid'.$kaType.'Widget',
    'settings'   => array(
        'ka_type'   => $kaType,
    ),
),
);


No, but you could assign settings => ka_type => BBQ before controller?


Well if u dont wana save value to variable first then u can do this .

save array on 2 steps.

$widgets = array(
'ka' => array(
    'name'       => 'Kool-Aid',
    'active'     => true,
    'priority'   => 10,
    'primacy'    => 30,
    'controller' => '',
    'settings'   => array(
        'ka_type'   => 'BBQ',
    ),
),
);
$widgets['ka']['controller'] = $widgets['ka']['settings']['ka_type'].'Widget';

OR if there is more than just Ka, u can loop it like

$widgets = array(
'ka' => array(
    'name'       => 'Kool-Aid',
    'active'     => true,
    'priority'   => 10,
    'primacy'    => 30,
    'controller' => '',
    'settings'   => array(
        'ka_type'   => 'BBQ',
    ),
),
);

Foreach($widgets as $name=>$val){
     $widget[$wid]['controller'] = $val['settings']['ka_type'].'Widget';
}

Hope it helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜