dongying9712 2019-01-15 20:34
浏览 81
已采纳

Substr不允许双位代码在表单上处理

I have an array that uses two codes in a list and pushes them into a form on the next page. Currently I have:

            $code= array();
            $code['c1'] = substr($part, 0, 1);
            $code['c2'] = substr($part, 2);

Now, If I select anything with a single digit c1 and single or double c2 then it adds to the form.

Examples:

1-9
1-15
9-12
9-9

But if I try to add anything with double digits in c1 it doesn't add, like:

10-1
10-2
10-11

If I try

$codes= array();
$codes['c1'] = substr($part, 0, 2);
$codes['c2'] = substr($part, 2);

Then no codes show up.

How can I account for both?

UPDATE:

Currently, the above code, if I select 10-58, will dump c1 as 1 and c2 as -5

  • 写回答

1条回答 默认 最新

  • dongxing1960 2019-01-15 20:47
    关注

    You can easily use explode() and list() to split any combination of codes...

    $part = "1-15";
    $codes = array();
    list($codes['c1'], $codes['c2']) = explode("-", $part);
    print_r($codes);
    

    gives...

    Array
    (
        [c1] => 1
        [c2] => 15
    )
    

    For

    $part = "10-15";
    

    it gives...

    Array
    (
        [c1] => 10
        [c2] => 15
    )
    

    If you are unsure if your data is always correct, you can check that the data has 2 components after using explode() and only convert it then, you can also do something to report and error or whatever you need...

    $split = explode("-", $part);
    if ( count($split) == 2 ){
        $codes['c1'] = $split[0];
        $codes['c2'] = $split[1];
    }
    else    {
        // Not of correct format.
    }
    
    print_r($codes);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载