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 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了