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

时间:2014-11-07 10:00:33

标签: php arrays json codeigniter

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

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

我需要在PHP中使用数组转换它。

6 个答案:

答案 0 :(得分:4)

该字符串看起来像有效的JSON,因此请使用json_decode

$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"
// }

如果您还需要将整数字符串转换为整数,请使用intvalarray_map

$array = array_map("intval", $array);
var_dump($array);

// array(4) {
//   [0]=>
//   int(50000001)
//   [1]=>
//   int(50000022)
//   [2]=>
//   int(50000043)
//   [3]=>
//   int(50000106)
// }

答案 1 :(得分:1)

试试这个 -

$str = '["50000001","50000022","50000043","50000106"]';

$arr = json_decode($str, true);

var_dump($arr);

答案 2 :(得分:1)

该字符串非常类似于JSON,因此您可以使用json_decode()

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

答案 3 :(得分:1)

您可以使用json_decode:

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

简单有效。

答案 4 :(得分:0)

看起来像JSON,所以你可以使用json_decode(),或者你可以查看explode函数。多一点搜索努力会带你到那里。

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

尽管如此,

$string = " ["50000001","50000022","50000043","50000106"]";
explode(",", $string);
//or
json_decode($string);

答案 5 :(得分:0)

试试这个:

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

如果您不需要引号,也可以使用:

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