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 如何用Thoony写ESP32温湿度检测无源蜂鸣器报警代码?
  • ¥20 部件内部的CT图像数据集
  • ¥15 Visual studio调用动态库
  • ¥15 双目摄像头标定后的校准文件
  • ¥15 powerbi矩阵增加度量值后出现对应关系错乱
  • ¥30 频率分析法分析绘制奈奎斯特图、波特图
  • ¥15 弹出来一万个系统找不到指定的文件框框,怎么解决
  • ¥15 ADS生成的微带线为什么是蓝色空心的
  • ¥15 求一下解题思路,完全不懂
  • ¥15 tensorflow