好的,所以有几种方法可以做到这一点......
方法一
如果您取出数组位并更适当地处理您的数据,那么正确的方法是:
SELECT `A`.`ID`, `A`.`Name`, `B`.`Value`
FROM A
INNER JOIN
`B` ON `A`.`ID` = `B`.`entryID`
ORDER BY `A`.`ID`, `B`.`Value`
这将返回如下结果:
array(
0 => array(ID=>1, Name=>'Jeff', Value=>'U.S'),
1 => array(ID=>1, Name=>'Jeff', Value=>'91725'),
2 => array(ID=>2, Name=>'Bob', Value=>'China')
)
你会像这样迭代它(你可以修改它来创建你所追求的数组结构,而不是回显到一个字符串......):
$mysqli = new mysqli(...);//Make your db connection
$query = $mysqli->query("
SELECT `A`.`ID`, `A`.`Name`, `B`.`Value`
FROM A
INNER JOIN
`B` ON `A`.`ID` = `B`.`entryID`
ORDER BY `A`.`ID`, `B`.`Value`
");
$newArr = array();
$lastID = '';
if($query->num_rows){
while($row = $query->fetch_assoc()){
if($lastID == $row['ID']){
end($newArr);
$key = key($newArr);
$newArr[$key][] = $row['Value'];
}
else{
$newArr[] = array($row['Name'], $row['Value']);
}
$lastID = $row['ID'];
}
}
var_export($newArr);
/**
Output:
array (
0 =>
array (
0 => 'Jeff',
1 => 'U.S.',
2 => '91275',
),
1 =>
array (
0 => 'Bob',
1 => 'China',
),
)
*/
方法二
如果您真的想要/需要从 中作为数组输出,SQL query
那么我建议您执行以下操作:
SELECT
A.ID, A.Name,
CONCAT(
'[',
GROUP_CONCAT('"', B.Value, '"'),
']'
) as Values
FROM A
INNER JOIN B ON B.entryID = A.ID
GROUP BY A.ID
这将输出Values
为json
:
array(
0=>arryay(ID=>1, Name=> 'Jeff', Values='["U.S.", "91725"]'),
1=>arryay(ID=>1, Name=> 'Bob', Values='["China"]')
)
并且您需要json_decode
在Values
每次访问php
. 就像是:
$mysqli = new mysqli(...);//Make your db connection
$query = $mysqli->query("
SELECT
A.ID, A.Name,
CONCAT(
'[',
GROUP_CONCAT('"', B.Value, '"'),
']'
) as Values
FROM A
INNER JOIN B ON B.entryID = A.ID
GROUP BY A.ID
");
$newArr = array();
if($query->num_rows){
while($row = $query->fetch_assoc()){
$newArr[] = array($row['Name']);
end($newArr);
$key = key($newArr);
$fieldData = json_decode($row['Values']);
foreach($fieldData as $value){
$newArr[$key][] = $value;
}
}
}
var_export($newArr);
/**
Output:
array (
0 =>
array (
0 => 'Jeff',
1 => 'U.S.',
2 => '91275',
),
1 =>
array (
0 => 'Bob',
1 => 'China',
),
)
*/
注意:我建议你不要这样做......因为如果你的数据没有以允许这样做的方式存储(例如,如果你没有编码/转义),它可能会导致各种错误"
)。B
如果从...中提取大量数据,您也可能会遇到问题。