简体   繁体   English

数组是否有内联“或”运算符?

[英]Is there an inline “OR” operator for arrays?

Is there any "inline" operator that can make this: 是否有任何“内联”运算符可以做到这一点:

$class_map = array(
    'a' => 'long text',
    'b' => 'long text',
    'c' => 'long text',
    'd' => 'other text',
    'e' => 'different text'
);

To be something like: 像这样:

$class_map = array(
'a' OR `b` OR `c` => 'long text'
'd' => 'other text',
'e' => 'different text'
);

I know about array_fill_keys() , but it's not really an "inline" solution, I want to be able to see/edit all my keys and values within the simple array . 我知道array_fill_keys() ,但这并不是真正的“内联”解决方案,我希望能够在简单array查看/编辑我所有的键和值。

No, there is no such operator specific to array keys. 不,没有特定于数组键的此类运算符。 However, there may be other ways to achieve what you may be after more simply by just taking advantage of the very nature of arrays in PHP. 但是,可能存在其他方法,仅通过利用PHP数组的本质即可更轻松地实现目标。

For example... 例如...

$class_map = [
    'a' => [
        'alias' => ['b','c',],
        'value' => 'long text',
    ],
    'd' => 'other text',
    'e' => 'different text',
];

Now your array could be read like this... 现在您的数组可以像这样读取...

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
    }
}

For the purposes of searching the aliases you could do something along the lines of... 为了搜索别名,您可以按照以下步骤进行操作:

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'];
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM