如何将字符串转换为数组?当我得到一个数组,但它是字符串格式

时间:2019-03-09 06:39:56

标签: php

当我wrong_predictions var $subject得到print时,我有一个echo $subject [["2","subject2","0","0"],["4","ccd","50","5"]]

但是当我做echo gettype($subject)时我得到string

因此,我无法使用foreach loop来遍历$subject

如何获取数组[["2","subject2","0","0"],["4","ccd","50","5"]]格式的

2 个答案:

答案 0 :(得分:1)

您可以使用json_decode将该字符串转换为数组:

$subject = '[["2","subject2","0","0"],["4","ccd","50","5"]]';
print_r(json_decode($subject, true));

输出:

Array ( 
    [0] => Array ( [0] => 2 [1] => subject2 [2] => 0 [3] => 0 ) 
    [1] => Array ( [0] => 4 [1] => ccd [2] => 50 [3] => 5 ) 
)

Demo on 3v4l.org

答案 1 :(得分:0)

如@nick所述,请使用json_decode函数将其设置为数组。

$subject = '[["2","subject2","0","0"],["4","ccd","50","5"]]';
$stringToArray = json_decode($subject, true);
foreach($stringToArray as $key => $value){
    print_r($value);echo '<hr>';
}