我正在寻找更好地理解如何使用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();
}
}
问题在于,即使每次迭代最多只有3个数组,但这可能更多,但我不想手动创建if($count == x…
我需要这是动态的。必须有更好的方法吗?
答案 0 :(得分:5)
您需要使用&
修饰符来set variables by reference而不是值。实际上,这意味着变量是另一个变量 - 对它的另一个引用。通过跟踪“根”对象并迭代由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 );
这将导致具有以下结构的数组,或者看到它running in this CodePad。
array(1) {
["Apparel, accessories & footwear"]=>
array(1) {
["Men's"]=>
array(3) {
["Apparel"]=>
array(0) {
}
["Footwear"]=>
array(0) {
}
["Accessories"]=>
array(0) {
}
}
}
}
答案 1 :(得分:0)
未经测试的代码:
$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);
$ptr = &$category;
for( $i = 0; $i < $count; $i++){
$ptr = &$ptr[$ex[$i]];
}
$ptr = array();
}