2013-06-28 141 views
1

所以這裏是我卡在的情況。我想從一個JavaScript文件(http://roosters-hd.stenden.com/js/data_autogen.js)導入一個多維數組在PHP中,我作爲一個字符串導入。它看起來像這樣:PHP中多維數組的字符串

locgrouparray[i++] = new locgroup("E0.090 (33)", "E0.090 (33)", "#SPLUS6ECDBE", "MET"); 
locgrouparray[i++] = new locgroup("E0.092 (28)", "E0.092 (28)", "#SPLUS6ECDBF", "(none)"); 
locgrouparray[i++] = new locgroup("E0.111 (30)", "E0.111 (30)", "#SPLUS6ECDC0", "(none)"); 
locgrouparray[i++] = new locgroup("E0.113 (30)", "E0.113 (30)", "#SPLUS6ECDC1", "(none)"); 
etc. 

到一個PHP數組:

Array (
    [0] => Array (
     [Class] => "E0.090 (33)" 
     [ClassID] => "#SPLUS6ECDBE"" 
     [type] => "MET" 
    ),  
    [1] => Array (
     [Class] => "E0.090 (28)" 
     [ClassID] => "#SPLUS6ECDBF"" 
     [type] => "(none)" 
    ), 
    [2] => Array (
     [Class] => "E0.111 (30)" 
     [ClassID] => "#SPLUS6ECDC0"" 
     [type] => "(none)" 
    ), 
    etc. 
) 

什麼是導入此多維數組的最有效方法是什麼?

+0

您要從哪個文件導入數據?我敢肯定你可以使用['file'](http://php.net/file)和其他一些函數的組合來創建一個循環來爲你做這個! – Dale

+2

這是非常不清楚什麼應該是一個數組在這裏,你想要的結果是什麼樣子。請澄清。 – deceze

+0

它的JavaScript,這裏是位置: http://roosters-hd.stenden.com/js/data_autogen.js – JasperJ

回答

1

您可以使用類似:

$data = file_get_contents('http://roosters-hd.stenden.com/js/data_autogen.js'); 
$matches = $outArray = array(); 

preg_match_all('#locgroup\("(.*?)"\);#', $data, $matches); 

foreach($matches[1] as $arr) { 
    array_push($outArray, explode('", "', $arr)); 
} 

print_r($outArray); 

輸出:http://pastebin.com/raw.php?i=ejxpUJy6

更新:如果你想如圖更新的問題你的陣列中使用的鍵名,只是改變了foreach環如下:

foreach($matches[1] as $arr) { 
    $tmp = explode('", "', $arr);   
    array_push($outArray, array(
     'Class' => $tmp[0], 
     'ClassID' => $tmp[2], 
     'type' => $tmp[3], 
    )); 
} 

輸出:http://pastebin.com/raw.php?i=ek0PRr0r

+0

完美的作品,謝謝! – JasperJ

1
$data = <<<DATA 
locgrouparray[i++] = new locgroup("E0.090 (33)", "E0.090 (33)", "#SPLUS6ECDBE", "MET"); 
locgrouparray[i++] = new locgroup("E0.092 (28)", "E0.092 (28)", "#SPLUS6ECDBF", "(none)"); 
locgrouparray[i++] = new locgroup("E0.111 (30)", "E0.111 (30)", "#SPLUS6ECDC0", "(none)"); 
locgrouparray[i++] = new locgroup("E0.113 (30)", "E0.113 (30)", "#SPLUS6ECDC1", "(none)"); 
DATA; 

preg_match_all('/locgroup\("([^"]+)",\s*"[^"]+",\s*"([^"]+)",\s*"([^"]+)"\)/i', $data, $matches, PREG_SET_ORDER); 
$parsedData = array_map(function (array $m) { return array('Class' => $m[1], 'ClassId' => $m[2], 'type' => $m[3]); }, $matches); 

var_dump($parsedData); 
+0

+1,用於更復雜的'array_map'解決方案。 ;-) – eyecatchUp