我从 MySQL 数据库中检索到这些数据:
现在我想从上面检索到的行创建以下数组...
任何想法如何做到这一点?蒂亚!
我从 MySQL 数据库中检索到这些数据:
现在我想从上面检索到的行创建以下数组...
任何想法如何做到这一点?蒂亚!
好吧,最简单的方法是在 PHP 代码中手动对数据进行分组,例如:
$stm = $db->query('SELECT * FROM tbl;');
$result = array();
while($row = $stm->fetch()) {
$result[$row['productcode']][] = $row['unit'];
}
var_dump($result);
使用对象结果,并使用 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;
}
运行此查询:
select productcode, group_concat(unitofmeasure separator ",") from product group by productcode
然后,当您在 PHP 中迭代结果时,使用该explode
函数。
$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
)
)
好吧,您尝试一下,这应该可以
$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++;
}