以下是我的表格:
units_main:
FACID----sub_key-----ASGMT_Name
AR01____1000_______LEGAL COMMAND
AR01____1001_______OPPS 67
AR02____1002_______REG D
units_sub:
FACID-----sub_key-----Long_Name
AR01_____1000_______cmd a, b and sometimes c
AR01_____1000_______secondary cmd structrue
AR01_____1001_______opps seg 798 b
AR02_____1002_______s cmd structure cc8
我通过URL到登录页面的$ _GET变量将FACID传递给查询,然后将$ _GET设置为$ _SESSION变量。基于此FACID,我想查询units_main,然后通过sub_key从units_sub连接记录。
Here's my query:
$real_facid = $_SESSION['facid'];
$query = "SELECT m.FACID
, m.sub_key
, m.ASGMT_Name
, s.Long_Name
FROM units_main AS m
LEFT OUTER
JOIN units_sub AS s
ON s.FACID = m.FACID
AND s.sub_key = m.sub_key
WHERE m.FACID = '$real_facid'
ORDER
BY m.FACID
, m.sub_key
, s.Long_Name";
这里我运行查询并获取数组:
$result = mysql_query($query) or die(mysql_error());
while ($rows = mysql_fetch_array($result)){
echo $rows['ASGMT_Name'];
echo $rows['Long_Name'];}
查询有效,但对于FACID = AR01,我得到以下结果:
LEGAL COMMAND
cmd a, b and sometimes c
LEGAL COMMAND
secondary cmd structrue
OPPS 67
opps seg 798 b
我希望返回的结果看起来像这样(注意第二个“LEGAL COMMAND”被删除):
LEGAL COMMAND
----cmd a, b and sometimes c
----secondary cmd structrue
OPPS 67
----opps seg 798 b
我知道我必须在阵列上循环,但我真的很挣扎......任何一点帮助都会受到赞赏!
感谢您的帮助!
编辑(12月6日) 这是最终的工作脚本:
$result = mysql_query($query) or die(mysql_error());
$res = array();
while ($rows = mysql_fetch_array($result))
{
//echo $rows['ASGMT_Name'];
if (!array_key_exists($rows['ASGMT_Name'], $res))
{
$res[$rows['ASGMT_Name']] = array();
}
//for some reason this didn't work?
//$values = $res[$rows['ASGMT_Name']];
$var = $rows['Long_Name'];
array_push($res[$rows['ASGMT_Name']],$var);
}
print_r($res);
我想在$ res数组的开头添加2个级别,即:
名称 - >分支 - > ASGMT_Name - > LONG_NAME
我尝试了这个,但它不起作用,'LEGAL COMMAND'需要在它之前成为数组的索引....:
$result = mysql_query($query) or die(mysql_error());
$res = array();
while ($rows = mysql_fetch_array($result))
{ //print_r($rows);
//echo $rows['ASGMT_Name'];
$res[$rows['name']] = array($rows['branch'] => array());
//$var = $rows['branch'];
//array_push($res[$rows['name']],$var);
if (!array_key_exists($rows['ASGMT_Name'], $res))
{
$res[$rows['ASGMT_Name']] = array();
}
$var = $rows['Long_Name'];
array_push($res[$rows['ASGMT_Name']],$var);
}
print_r($res);
以下是上述输出:
Array ( [name] => Array ( [branch] => Array ( ) )[LEGAL COMMAND] =>
Array ( [0] => cmd a, b and sometimes c [1] => cmd a, b and sometimes c)
任何帮助?
再次感谢!
答案 0 :(得分:0)
你需要像
这样的东西$res = array();
while ($rows = mysql_fetch_array($result))
{
if (!array_key_exists($res, $rows['ASGMT_Name']))
{
$res[$rows['ASGMT_Name']] = array();
}
$values = $res[$rows['ASGMT_Name']];
array_push($values,$rows['Long_Name'];)
}
现在,您在$res
中有分层数据。