F
F
fustaska2020-09-22 16:27:28
PHP
fustaska, 2020-09-22 16:27:28

How to convert string to array with "[]"?

Greetings. I have a global one that I still can't solve :((
There is a line: "[{'CS': 3, 'CV': 9, 'V': 9}, {'CS': 0, 'CV ': 13, 'V': 4}, {'CS': 0, 'CV': 6, 'V': 6}]", I have already tried everything to extract melons in json format ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alams Stoyne, 2020-09-22
@fustaska

Create Json

$temp_arr = [
    ['CS'=> 3, 'CV'=> 9, 'V' => 9],
    ['CS'=> 3, 'CV'=> 9, 'V' => 9],
    ['CS'=> 3, 'CV'=> 9, 'V' => 9],
];
$json_temp = json_encode($temp_arr);
var_dump($json_temp );

Get
string(68) "[{"CS":3,"CV":9,"V":9},{"CS":0,"CV":13,"V":4},{"CS":0,"CV":6,"V":6}]"

Now we look at your line and understand that the trouble is in quotes .... use the code:
$text = "[{'CS': 3, 'CV': 9, 'V': 9}, {'CS': 0, 'CV': 13, 'V': 4}, {'CS': 0, 'CV': 6, 'V': 6}]"; 
$array = json_decode(str_replace('\'','"',$text)); 
var_dump($array);

At the output we get:
array(3) {
  [0]=>
  object(stdClass)#1 (3) {
    ["CS"]=>
    int(3)
    ["CV"]=>
    int(9)
    ["V"]=>
    int(9)
  }
  [1]=>
  object(stdClass)#2 (3) {
    ["CS"]=>
    int(0)
    ["CV"]=>
    int(13)
    ["V"]=>
    int(4)
  }
  [2]=>
  object(stdClass)#3 (3) {
    ["CS"]=>
    int(0)
    ["CV"]=>
    int(6)
    ["V"]=>
    int(6)
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question