多维爆炸();制表符分隔的顺序数组键字符串

时间:2011-05-25 23:08:33

标签: php arrays multidimensional-array

我正在使用Drupal中的视图,并且已经获得了如下字符串:

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

1 个答案:

答案 0 :(得分: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个房间。如果你有一个函数在“rooms”中拆分字符串并返回一个房间数组,并使用strpos(),这可能会更好。

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

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

相关问题