doulan9287
2014-11-07 10:00
浏览 57

如何在php中转换数组中的逗号分隔值

I have one string contains numbers and i need to convert it in an array. My string is:

["50000001","50000022","50000043","50000106"]

And i need to convert it in an array in PHP.

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

我有一个字符串包含数字,我需要将其转换为数组。 我的字符串是:

  [“50000001”,“50000022”,“50000043”,“50000106”] 
   
 
 <  p>我需要在PHP中用数组转换它。 
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

6条回答 默认 最新

  • dtjzpg5313 2014-11-07 10:03
    已采纳

    That string pretty much looks like JSON, so you could use json_decode():

    $input = '["50000001","50000022","50000043","50000106"]';
    $arr = json_decode( $input );
    
    已采纳该答案
    打赏 评论
  • duanlu4371 2014-11-07 10:01

    Try this -

    $str = '["50000001","50000022","50000043","50000106"]';
    
    $arr = json_decode($str, true);
    
    var_dump($arr);
    
    打赏 评论
  • doushi3819244 2014-11-07 10:03

    Looks like JSON, so you can use json_decode(), or you can look up to the explode function. A little more search effort would have brought you there.

    http://php.net/manual/en/function.explode.php

    None the less,

    $string = " ["50000001","50000022","50000043","50000106"]";
    explode(",", $string);
    //or
    json_decode($string);
    
    打赏 评论
  • doulv8162 2014-11-07 10:03

    Try this:

    $string = '["50000001","50000022","50000043","50000106"]';
    var_dump(explode(",", trim($string, "[]")));
    

    If you do not need the quotes, you can also use this:

    $string = '["50000001","50000022","50000043","50000106"]';
    $array = str_replace('"', '', explode(",", trim($string, "[]")));
    var_dump($array);
    
    打赏 评论
  • douyulv6921 2014-11-07 10:03

    You can use json_decode:

    $array = json_decode('["50000001","50000022","50000043","50000106"]');
    

    Simple and effective.

    打赏 评论
  • douguluan5102 2014-11-07 10:03

    The string looks like valid JSON, so use json_decode for this:

    $array = json_decode('["50000001","50000022","50000043","50000106"]');
    var_dump($array);
    
    // array(4) {
    //   [0]=>
    //   string(8) "50000001"
    //   [1]=>
    //   string(8) "50000022"
    //   [2]=>
    //   string(8) "50000043"
    //   [3]=>
    //   string(8) "50000106"
    // }
    

    If you also need to convert the integers-as-strings to integers, use intval and array_map:

    $array = array_map("intval", $array);
    var_dump($array);
    
    // array(4) {
    //   [0]=>
    //   int(50000001)
    //   [1]=>
    //   int(50000022)
    //   [2]=>
    //   int(50000043)
    //   [3]=>
    //   int(50000106)
    // }
    
    打赏 评论

相关推荐 更多相似问题