是否有内联" OR"数组的运算符?

时间:2016-01-23 14:20:04

标签: php arrays

是否有"内联"可以做到这一点的运营商:

$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中查看/编辑我的所有键和值。

1 个答案:

答案 0 :(得分:0)

不,没有特定于数组键的运算符。但是,通过利用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'];
        }
    }
}