0

I have a number of strings, that contain the bracket literals:

0 => string '[139432,97]' (length=18)
1 => string '[139440,99]' (length=18)

I need to create string arrays of [139432,97] and [139440,99].

I've tried using json_decode(), but while it works, it creates arrays as float or int using the above data, however I want them as strings.

array (size=2)
0 => float 139432
1 => int 97

array (size=2)
0 => float 139440
1 => int 97
yoyoma
  • 3,336
  • 6
  • 27
  • 42

3 Answers3

1

You can put double quotes around the values e.g.

0 => string '["139432","97"]' (length=22)
1 => string '["139440","99"]' (length=22)

This way when you json_decode they should be strings.

Edit:

OK I thought you could control the input - if not then a simple trim and explode could do:

explode(',', trim('[139432,97]', '[]'));

array(2) {
  [0]=>
  string(6) "139432"
  [1]=>
  string(2) "97"
}

Is that enough?

user2910443
  • 111
  • 3
1

Just combining what you already now (json_decode) and what @AlixAxel suggested here you can extract those values to string link:

$subject = '[139432,97]';
$convertedToArrayOfStrings = array_map('strval', json_decode($subject));

or

$convertedToArrayOfString = array_map(function($item){return (string) $item;}, json_decode($subject));

for better performance, see the comment bellow please :)

Community
  • 1
  • 1
Ali
  • 2,993
  • 3
  • 19
  • 42
  • 1
    And if you are concern about performance, based on what i just learned from @KimHogeling's comment on [here](http://stackoverflow.com/questions/7371991/php-string-cast-vs-strval-function-which-should-i-use) and [this](http://leifw.wickland.net/2009/08/performance-of-converting-integer-to.html) you can replace the **strval** with an anonymous method and cast your values e.g. `$convertedToArrayOfString = array_map(function($item){return (string) $item;}, json_decode($subject));` – Ali Jun 09 '15 at 14:47
0

Why not try with loop and use explode function:

$array = array('139432,97', '139440,99');
$finalArray = array();

$i = 0;
foreach ($array as $arr) {
    $explode = explode(",", $arr);
    $j = 0;
    foreach ($explode as $exp) {
       $finalArray[$i][$j] = (int)$exp;
       $j++;
    }
    $i++;
}
chandresh_cool
  • 11,753
  • 3
  • 30
  • 45
  • I had tried explode, but because the data is coming externally, the brackets are included, so I would need to massage it further, to use what you have on first line – yoyoma Jun 09 '15 at 14:14