dongmi4035 2015-02-17 02:17
浏览 40

如何使用PHP将base10数字转换为数组

The meaning is : How to store in a single database field, multiple value as, for example, Optin data.

In order to do that, i've to know how to code and decode the value. I've an array with different optin values:

$optin = array (
    '1' => 'SMS',
    '2' => 'Email',
    '4' => 'Mail',
    '8' => 'AppsPushNotif',
    '16' => 'Partners',
    '32' => 'Gaming Partners'
);

ie.: I'll store,in optin field : - '7' if the user is opt-in for SMS,Email and Mail (4+2+1) or - '40' for AppsPushNotif and Gaming_Partners

I would like found a way to decode 7 or 40 values into an array with optin's arrays values.

Many thanks

PS: Thanks to Cyclone for the solution :

$output = '';
$value = 40;
$keys = array_keys($food);  

foreach($keys as $key) {   
    if($value & $key) $output .= $food[$key].',';  
}  

print rtrim($output, ',');
  • 写回答

2条回答 默认 最新

  • doucuyu2259 2015-02-19 18:17
    关注

    A solution in one line to unpack $value into individual values that appear as keys in $optin:

    $value = 40;
    
    $keys = array_map(
        function($i) { return 1 << $i; },
        array_keys(array_filter(str_split(strrev(decbin($value)))))
    );
    
    print_r($keys);
    

    The output is:

    Array
    (
        [0] => 8
        [1] => 32
    )
    
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)