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

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

图片转代码服务由CSDN问答提供 功能建议

我有一个数组,它在列表中使用两个代码并将它们推送到下一页的表单中。 目前我有:

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

现在,如果我选择任何一个数字 c1 并且单个 或者双 c2 然后它会添加到表单中。

示例:

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

但如果我尝试在c1中添加两位数的任何内容,则不会添加,例如:

  10-1 
10-2 
10-11 
   
 
 

如果我尝试 < pre> $ codes = array(); $ codes ['c1'] = substr($ part,0,2); $ codes ['c2'] = substr($ part,2);

然后没有代码出现。

我如何解释两者? < p> UPDATE:

目前,上面的代码,如果我选择10-58,将把c1转为1,c2转为-5

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongxing1960
    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);
    
    点赞 评论

相关推荐