You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何将数组值转换为管道分隔的位运算值而非字符串供json_encode使用

你实际需要的是计算数组中所有值的按位或运算结果,因为json_encode的第二个参数本身接受整数类型的位掩码,不需要拼接为字符串形式的表达式。

实现方式1:循环遍历累加(兼容所有PHP版本)

$bitmask = 0;
foreach ($json_options as $option) {
    $bitmask |= $option;
}

// 直接传入计算得到的整数值即可
json_encode($data, $bitmask);

实现方式2:array_reduce 简写(PHP 5.6及以上版本支持)

$bitmask = array_reduce($json_options, function($carry, $item) {
    return $carry | $item;
}, 0);

// PHP 7.4+ 可以用箭头函数更简洁
// $bitmask = array_reduce($json_options, fn($c, $i) => $c | $i, 0);

json_encode($data, $bitmask);

如果你确实需要生成1 | 2 | 4 | 8格式的代码字符串(例如用于代码生成场景),不想用implode的话可以按如下方式实现:

$expr = '';
foreach ($json_options as $index => $val) {
    if ($index !== 0) {
        $expr .= ' | ';
    }
    $expr .= $val;
}

内容的提问来源于stack exchange,提问作者kodfire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 04:15:06