是否有任何"内联"运算符可以做到这一点:
$class_map = array(
'a' => 'long text',
'b' => 'long text',
'c' => 'long text',
'd' => 'other text',
'e' => 'different text'
);
像这样:
$class_map = array(
'a' OR `b` OR `c` => 'long text'
'd' => 'other text',
'e' => 'different text'
);
我知道array_fill_keys()
,但它并不是真正的"内联"解决方案,我希望能够在简单的array
中查看/编辑我的所有键和值。
不,没有特定于数组键的此类运算符。但是,可能还有其他方法可以更简单地利用 PHP 中数组的本质来实现您所追求的目标。
例如。。。
$class_map = [
'a' => [
'alias' => ['b','c',],
'value' => 'long text',
],
'd' => 'other text',
'e' => 'different text',
];
现在你的数组可以这样读...
foreach($class_map as $key => $value) {
if (is_array($value)) {
// has aliases...
foreach($value['alias'] as $v) {
// do stuff with aliases here
}
} else {
// has no aliases
}
}
为了搜索别名,您可以执行以下操作
...function searchClassMap($className, Array $class_map)
{
if (isset($class_map[$className])) {
// if the className already is a key return its value
return is_array($class_map[$className])
? $class_map[$className]['value']
: $class_map[$className];
}
// otherwise search the aliases...
foreach($class_map as $class => $data) {
if (!is_array($data) || !isset($data['alias'])) {
continue;
}
if (in_array($className, $data['alias'])) {
return $data['value'];
}
}
}