我有一个像这样的SQL查询:
SELECT name, rbl.locationlabel FROM `pages` INNER JOIN locations as rbl ON rbl.locationId = pages.locationId
这将返回一个名称列表和一个locationlabel,locationlabel将是“位置A”,“位置B”或“位置C”我所拥有的是:
$query = mysqli_query($connection, "SELECT name, rbl.locationlabel FROM `pages` INNER JOIN locations as rbl ON rbl.locationId = pages.locationId");
$results = array();
$results['location'] = array();
while($row = mysqli_fetch_assoc($query)){
$results[] = $row;
}
return $results;
这将遍历结果并将其放入数组中,我要做的是在结果数组中有另一个数组或数组,以获得每个位置并具有分配给该位置的名称。 / p>
非常感谢。
答案 0 :(得分:0)
假设name
字段是唯一的,您可以简单地使用:
while($row = mysql_fetch_assoc($query)) {
$results[$row['name']] = $row;
}
但如果你重复名字,那么你需要一些更高级的逻辑,比如创建子阵列:
$results[$row['name']][] = $row;
答案 1 :(得分:0)
您可以这样做:
<?php
$con=mysqli_connect("localhost","root","","abc1");
if($con)
{
$i=0;
$query="select distinct location from locations";
$result=mysqli_query($con,$query);
while($re=mysqli_fetch_array($result))
{
$x[]=$re;
}
}
$m=array();
for($i=0;$i<3;$i++)
{
$query="SELECT name FROM `pages` INNER JOIN locations as rbl ON rbl.locationId = pages.locationId";
$z=$x[$i]['location'];
echo $query;
$result=mysqli_query($con,$query);
while($re=mysqli_fetch_array($result))
{
foreach($re as $q)
$m["'".$z."'"][]=$q;
}
}
print_r($m);
?>
它将名称存储在索引为位置名称的数组中。
示例输出:
Array ( ['A'] => Array ( [0] => John [1] => Jim [2] => Jack)
['B'] => Array ( [0] => Joseph [1] => Mary )
['C'] => Array ( [0] => Bale [1] => Cyrus [2] => Mike [3] => Rhode ) )
您可以使用name_of_array['location_name'][number of name records]
希望它有所帮助。