动态多维数组

时间:2013-11-16 05:44:23

标签: php mysql multidimensional-array

我一直试图弄清楚如何创建动态多维数组。

原因是我想创建一个将从mysql动态创建的下拉菜单

示例数据库

|id|menu_name|menu_parent_id|

|1 |top menu1|      0       |

|2 |top menu2|      0       |

|3 |top menu3|      0       |

|4 |top menu4|      0       |

|5 |sub menu |      2       |

|6 |sub menu |      2       |

|7 |sub menu |      5       |

|8 |sub menu |      6       |

|9 |top menu |      0       |

我想从没有父母的菜单开始然后把它放在一个数组

$parentIDs[0]=0;
$tempParentIDs = array();
$childIDs = array();
$menus = array();
$rows = 0;

$rows=0;
foreach($parentIDs AS $value){
$sql = mysql_query("SELECT * FROM service WHERE service_parent_id=$value");
while($temp = mysql_fetch_array($sql)){

    //$tempParentIDs[] = $temp['service_id'];

    //check if parent have child
    $sql2 = mysql_query("SELECT * FROM service WHERE  service_parent_id=$temp[service_id]") or die(mysql_error());
    $rows = mysql_num_rows($sql2);
    if($rows >= 1){
        //This means there is a child
        while($temp2 = mysql_fetch_array($sql2)){
            $childIDs[] = $temp2['service_id'];
        }

        $tempParentIDs[$temp['service_id']] = $childIDs;
        unset($childIDs);
    } else {
        //This means there is no child
    }
}
}

echo "<pre>";
print_r($tempParentIDs);
echo "</pre>";

但在那之后我被卡住了。

2 个答案:

答案 0 :(得分:1)

我认为你正在寻找这个:

$parentIDs[0]=0;
$tempParentIDs = array();
$childIDs = array();
$menus = array();
$rows = 0;
$multiDimensionalArray = NULL; //here I made change - vijay

$rows=0;
foreach($parentIDs AS $value){
$sql = mysql_query("SELECT * FROM service WHERE service_parent_id=$value");
while($temp = mysql_fetch_array($sql)){

    $tempParentIDs = $temp['service_id']; //here I made change - vijay

    //check if parent have child
    $sql2 = mysql_query("SELECT * FROM service WHERE  service_parent_id=$temp[service_id]") or die(mysql_error());
    $rows = mysql_num_rows($sql2);
    if($rows >= 1){
        //This means there is a child
        while($temp2 = mysql_fetch_array($sql2)){
            $multiDimensionalArray[$tempParentIDs][] = $temp2['service_id']; //here I made change - vijay
        }

       // $tempParentIDs[$temp['service_id']] = $childIDs; //here I made change - vijay
       // unset($childIDs); //here I made change - vijay
    } else {
        //This means there is no child
    }
}
}

echo "<pre>";
print_r($multiDimensionalArray); //here I made change - vijay
echo "</pre>";

答案 1 :(得分:0)

你应该像这样在php中存储数组: 这可能对你有用

$next = 0;

$level = 0;

$sql = mysql_query("SELECT * FROM service WHERE service_parent_id=$next");

$temps = array();

while($temp = mysql_fetch_array($sql))
{
$temps[] = $temp;
}

foreach($temps as $temp)
{
echo $temp['service_id'];
}