一次性将键/值对动态应用于数组(在第一个定义中)


Dynamically apply a key/value pair to an array in one go (within first definition)

想象一下这种情况:

$component = array(
    'type' => 'chimney',
    'material' => 'stone'
);

如果满足某个条件,我想做的是向这个数组添加一个键/值对。

$hasMetrics = true;
$component = array(
    'type' => 'chimney',
    'material' => 'stone',
    'metrics' => ($hasMetrics ? array('width' => 60, 'height' => 2000) : false)
);

虽然这是可以使用的,但它总是会在我的数组中导致一个名为"metrics"的键。

当然,如果我不想这样,我可以使用array_merge()将第二个数组与第一个数组合并(第二个是空数组或所需的键/值对,具体取决于条件)。

但我想知道的是,是否有任何方法可以像上面那样定义这个数组,同时处理$hasMetrics,而不使用任何其他方法(如array_merge()),而是纯粹在这个数组的实际(第一个也是唯一的)定义中。

像这样:(不适用,示范性示例)

$component = array(
    'type' => 'chimney',
    'material' => 'stone',
    ($hasMetrics ? array('metrics' => array(
        'width' => 60,
        'height' => 2000
    )) : false)
);

(据我所知,这将生成两个密钥(typematerial),然后创建一个无键值,也就是说,它本身就是一个包含一个密钥的数组(metrics)和另一个数组作为值。)

有人能告诉我一些正确的方法吗?也许有某种PHP函数可用,具有特殊的属性(例如能够交叉分配的list())。

编辑

也许还需要更多的澄清,因为许多答案指出了前进的道路,例如:

  • 对某个密钥进行后续分配
  • 定义生成的数组后对其进行筛选

虽然这些都是扩展数组的非常有效的方法,但我明确地在one数组定义中寻找一种一次性完成的方法。

不使用数组防御本身。如果需要,我会将其添加到阵列中:

if($hasMetrics) {
    $component['metrics'] = array('width' => 60, 'height' => 2000);
}
$hasMetrics = true;
$component = array(
    'type' => 'chimney',
    'material' => 'stone',
);
if($hasMetrics){
     $component['metrics'] = array('width' => 60, 'height' => 2000);
}

尝试

$component = array(
    'type' => 'chimney',
    'material' => 'stone',
    'metrics' => $hasMetrics ? array('width' => 60, 'height' => 2000) : ''
);

在之后

$component = array_filter( $component ); // remove if it has '' value

  $component = array(
        'type' => 'chimney',
        'material' => 'stone',
    );

if($hasMetrics) {
    $component['metrics'] = array('width' => 60, 'height' => 2000);
}