2015-09-04 124 views
3

你好堆栈溢出,
这是我的第一篇文章,我有一个问题,我需要解析这个文本,并将其变成一个数组(它从数据库)。PHP解析表/数组字符串

"TableToKeyValues" 
{ 
    "inventory" 
    { 
     "slot2" 
     { 
      "amount"  "10" 
      "item"  "wood_plank" 
     } 
     "slot1" 
     { 
      "amount"  "10" 
      "item"  "metal" 
     } 
     "slot3" 
     { 
      "amount"  "10" 
      "item"  "plastic" 
     } 
    } 
} 

谢谢rtm516。

回答

3

我计算出如何通过格式化成JSON期运用的时间很多str_replace函数来做到这一点。

$inv = preg_replace("/\r|\n/", "", $inv); 
$inv = str_replace('}', '},', $inv); 
$inv = str_replace('"  "', '":"', $inv); 
$inv = str_replace('"   "', '","', $inv); 
$inv = str_replace('"  {', '":{', $inv); 
$inv = str_replace('" {', '":{', $inv); 
$inv = str_replace('"{', '":{', $inv); 
$inv = trim(preg_replace('/\t+/', '', $inv)); 
$inv = str_replace('},}', '}}', $inv); 
$inv = str_replace('},},', '}}', $inv); 
$inv = str_replace('"TableToKeyValues":', '', $inv); 
$inv = json_decode($inv, true); 

编辑:$ inv是来自数据库的值。

0

如果你想,要转换成array使用json_decode

$arr = json_decode($dataComingFromDBHERE, true); 
print_r($arr); 
+0

这看起来不像JSON ... –

+0

它没有,并没有工作。感谢您的尝试 – rtm516

+0

我认为这是一个JSON。数据来自哪里?在插入数据库之前。 – aldrin27