2011-05-25 56 views
0

我正在与在Drupal一个视图中工作,并已获得如下所示的字符串的制表符分隔的字符串:Multidimensionally explode();序贯数组键

Room: Bedroom Length: 5.00 Width: 5.00 Area: 25.00 Room: Bathroom Length: 3.00 Width: 3.00 Area: 9.00 

这是为两个“房间”的对象,每一个长度,宽度和面积。

我怎么会爆炸到这个多维数组类似如下:

array([0] => array([room] => "Bedroom" [length] => "5.00" [width] => "5.00" [area] => "25.00") 
     [1] => array([room] => "Bathroom" [length] => "3.00" [width] => "3.00" [area] => "9.00")) 

回答

0

如你所知,第一步是把字符串中的变量,能够与它玩。然后,您将分割“房间”上的字符串,但我将继续此示例,就好像每个$ spec都有2个房间一样。

//need the string in a variable .... 
$specs = "Room: Bedroom Length: 5.00 Width: 5.00 Area: 25.00 Room: Bathroom Length: 3.00 Width: 3.00 Area: 9.00"; 

//Explode your string on space caracter: 
$specs_exploded = explode(" ", $specs); 

// Then, call the following function to build your array: 
$specs_array = build_specs($specs_exploded); 

// Function that builds and returns specs_array. 
function build_specs(Array $specs){ 

    $spec_array = array(); 

    $spec_array[] = array("room" => $specs[1], 
          "length" => $specs[3], 
          "width" => $specs[5], 
          // you could also set the key programmaticaly... 
          // the following woud give you "Area" => 25.00 
          $specs[6] => $specs[7], 
         ); 

        // Second room 
    $spec_array[] = array("room" => $specs[9], 

         // etc... 
         ); 
    return $spec_array; 
} 

请注意,示例函数专门处理2个房间。如果你有一个函数在“房间”中分割字符串并返回一个带有strpos()的房间数组,这可能会更好。

将返回的个房间数组传递给以上只能一次处理一个房间的示例函数的一个版本。

希望这足以让你滚动,祝你好运!

+0

我最后只是重做视图,以便对象实际上作为对象流动,而不是具有奇怪分隔符字符的字符串;我需要为我正在使用的复杂字段类型创建关系。无论如何,接受你的答案,因为我可能会用你的代码,我继续这样。 – aendrew 2011-05-29 09:36:13