我从MySQL数据库中检索到这些数据:
现在我想从上面检索到的行创建以下数组......
任何想法如何做到这一点? TIA!
答案 0 :(得分:2)
嗯,最简单的方法是在PHP代码中手动分组数据,例如:
$stm = $db->query('SELECT * FROM tbl;');
$result = array();
while($row = $stm->fetch()) {
$result[$row['productcode']][] = $row['unit'];
}
var_dump($result);
答案 1 :(得分:0)
使用对象结果,并使用mysqli(或其他任何购买mysql)
$my_array = array();
// Run Query here to get $result
while ($obj = mysqli_fetch_object($result)) {
$my_array[$obj->Product_Code][] = $obj->Unit_Of_Measure;
}
答案 2 :(得分:0)
运行此查询:
select productcode, group_concat(unitofmeasure separator ",") from product group by productcode
然后,当您在PHP中迭代结果时,请使用explode
函数。
答案 3 :(得分:0)
$result = mysql_query("select * from stack");
$my_array = array();
// Run Query here to get $result
while ($obj = mysql_fetch_array($result)) {
$my_array[$obj['product_code']][] = $obj['unit'];
}
echo "<pre>";
print_r($my_array);
echo "</pre>";
exit;
输出
Array
(
[1111] => Array
(
[0] => piece
[1] => case
)
[2222] => Array
(
[0] => piece
)
[3333] => Array
(
[0] => piece
)
[8888] => Array
(
[0] => box
[1] => pack
[2] => piece
)
)
答案 4 :(得分:0)
你试试这个,这应该有用
$rs = mysql_query('SELECT * FROM tbl order by product_code asc');
$arr = array();
$num = 0;
$strTemp = '';
while($data = mysql_fetch_object($rs)) {
if ($strTemp != $data->product_code) {
$strTemp = $data->product_code;
$num = 0;
}
$arr[$strTemp][$num] = $data->unit_of_measure;
$num++;
}