1

So here is the situation i'm stuck at. I'm trying to import a multidimensional array in PHP from a javascript file(http://roosters-hd.stenden.com/js/data_autogen.js) which i import as a string. It looks like this:

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.

Into a php array:

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.  
)

What would be the most efficient way to import this multidimensional array?

4

2 回答 2

1

You could use something like:

$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);

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

Update: If you want your array to use the key names as shown in your updated question, just change the foreach loop as follows:

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

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

于 2013-06-28T08:38:50.677 回答
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);
于 2013-06-28T08:51:16.147 回答