我正在寻找一个更好的理解如何使用while循环更有效地堆叠数组?
我有这个旧的数组,我需要迭代,爆炸每个,并创建一个多维数组.有没有更好的方法以编程方式执行此操作?
$cat[] = "Apparel, accessories & footwear";
$cat[] = "Apparel, accessories & footwear/Men's";
$cat[] = "Apparel, accessories & footwear/Men's/Apparel";
$cat[] = "Apparel, accessories & footwear/Men's/Footwear";
$cat[] = "Apparel, accessories & footwear/Men's/Accessories";
foreach($cat as $cs){
$ex = explode("/",$cs);
$count = count($ex);
if($count == 1){
$category[$ex[0]] = array();
}
if($count == 2){
$category[$ex[0]][$ex[1]] = array();
}
if($count == 3){
$category[$ex[0]][$ex[1]][$ex[2]] = array();
}
if($count == 4){
$category[$ex[0]][$ex[1]][$ex[2]][$ex[3]] = array();
}
if($count == 5){
$category[$ex[0]][$ex[1]][$ex[2]][$ex[3]][$ex[4]] = array();
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,即使每次迭代最多只有3个数组,但这可能更多,但我不想手动创建,if($count == x…我需要这个是动态的.肯定有更好的办法?
您需要使用&修饰符通过引用而不是值来设置变量.实际上,这意味着变量是另一个变量 - 对它的另一个引用.通过跟踪"根"对象并迭代由explode()您可以映射到$category数组的数组,以设置所需的多个级别.
$cat = array();
$cat[] = "Apparel, accessories & footwear";
$cat[] = "Apparel, accessories & footwear/Men's";
$cat[] = "Apparel, accessories & footwear/Men's/Apparel";
$cat[] = "Apparel, accessories & footwear/Men's/Footwear";
$cat[] = "Apparel, accessories & footwear/Men's/Accessories";
// initialize array to track categories
$category = array();
// keep track of the root so we can reset it after each loop
$root = &$category;
foreach( $cat as $cs ){
$exes = explode( "/", $cs );
foreach ( $exes as $ex ){
// get rid of spaces
$ex = trim( $ex );
// if this element isn't set at this level, add it
if ( ! isset( $category[$ex] ) ){
$category[$ex] = array();
}
// map down a level for the next loop
$category = &$category[$ex];
}
// reset back to the $root for the next $cat
$category = &$root;
}
var_dump( $category );
Run Code Online (Sandbox Code Playgroud)
这将导致具有以下结构的阵列,或者看到它在此CodePad中运行.
array(1) {
["Apparel, accessories & footwear"]=>
array(1) {
["Men's"]=>
array(3) {
["Apparel"]=>
array(0) {
}
["Footwear"]=>
array(0) {
}
["Accessories"]=>
array(0) {
}
}
}
}
Run Code Online (Sandbox Code Playgroud)