0

I have a string "[[10,20],[30,40],[50,30]]" which can be converted into array by simply using json_decode which works fine for numeric values but it's failing for string values like "[S,M,L]" which I handled using a simple logic.

$string_value = str_replace(',', '","', $string_value); $string_value = str_replace('[', '["', $string_value); $string_value = str_replace(']', '"]', $string_value); $string_value = json_decode($string_value); 

This works fine for a one dimensional array like the one given above, but in case of a 2d array like [[red,green],[red],[red,blue]] it's failing.

3
  • Well you could replace ["[ with [[ and ]"] with ]] at the end Commented Mar 6, 2017 at 19:47
  • 4
    Why are you getting strings like that that aren't encoded properly? I would look at the other end and fix it. Commented Mar 6, 2017 at 19:48
  • 2
    Trying to write your own parser for a non-standardized format, you'll always run into problems, exceptions, etc. Is there no way you can fix the input? Commented Mar 6, 2017 at 19:48

2 Answers 2

3

A regex replacement would work to wrap all alphabetical characters in quotes:

$value = preg_replace( "(\w+)", '\'$0\'', $input ); 

Like so:

<?php $input1 = "[[10,20],[30,40],[50,30]]"; $input2 = "[[red,green],[red],[red,blue]]"; $value1 = preg_replace( "(\w+)", '\'$0\'', $input1 ); $value2 = preg_replace( "(\w+)", '\'$0\'', $input2 ); echo $value1; echo "<br />"; echo $value2; ?> 

Gives me this output:

[['10','20'],['30','40'],['50','30']] [['red','green'],['red'],['red','blue']] 
Sign up to request clarification or add additional context in comments.

3 Comments

Good idea, will deliver a solution, but this is not yet an answer to the question!
This will not give you valid json, although that is easily fixed. The bigger problem will be the follow-up questions: Oh, but the string can contain spaces. And special characters. And of course, the keys can be strings was well ;-)
[["'red'","'green'"],["'red'"],["'red'","'blue'"]] my o/p
0

To convert the string to a 1 Dimension Array fisrt remove the brackets and then only having a string separated by commas use the explode function:

$result=str_replace(array('[',']'),'',$original_string); $result=explode(',',$result); 

This can help is input are only 2D arrays:

$final_array=array(); // separate each brackets $separate_in_arrays=explode(',',$osiginal_string); foreach ($separate_in_array as $array) { $result=str_replace(array('[',']'),'',$array[0]); $result=explode(',',$result); // Save result in a nested array $final_array[]=$result; } 

3 Comments

This doesn't work because there are nested arrays, this approach will flatten the array.
Yes indeed. This a solution to create a 1 dimensional array.
Editted solution to create a 2D Array from the sample string

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.