我正在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"))
如您所知,第一步是将字符串放入一个变量中,以便能够使用它。然后,您可以在"Room"上拆分字符串,但我将继续这个示例,就好像每个$spec都有两个房间一样。
//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()将字符串拆分为"rooms"并返回一个rooms数组,情况会更好。
将返回的rooms数组传递给一次只处理一个房间的上述示例函数的版本。
希望这足以让你继续前进,祝你好运!