意思是:如何在单个数据库字段中存储多个值,例如Optin数据。
为了做到这一点,我必须知道如何对值进行编码和解码。我有一个不同optin值的数组:
$optin = array (
'1' => 'SMS',
'2' => 'Email',
'4' => 'Mail',
'8' => 'AppsPushNotif',
'16' => 'Partners',
'32' => 'Gaming Partners'
);
即:我将在optin字段中存储:-"7",如果用户选择使用短信、电子邮件和邮件(4+2+1)或-AppsPushNotif和Gaming_Partners 的"40"
我想找到一种方法,用optin的数组值将7或40个值解码成一个数组。
非常感谢
PS:感谢Cyclone提供的解决方案:
$output = '';
$value = 40;
$keys = array_keys($food);
foreach($keys as $key) {
if($value & $key) $output .= $food[$key].',';
}
print rtrim($output, ',');
一行中的解决方案,用于将$value
解压缩为在$optin
:中显示为键的各个值
$value = 40;
$keys = array_map(
function($i) { return 1 << $i; },
array_keys(array_filter(str_split(strrev(decbin($value)))))
);
print_r($keys);
输出为:
Array
(
[0] => 8
[1] => 32
)
这应该有效:
$output = '';
$value = 40;
$keys = array_keys($food);
foreach($keys as $key) {
if($value & $key)
$output .= $food[$key].',';
}
print rtrim($output, ',');