[英]Associative Array PHP Random values
我有关于php中的关联多维数组的任务。
假设我有下表:
Product Nr Img
kat1 abc abc.png
kat1 xyz xyz.png
kat2 def def.png
kat2 gfh gfh.png
kat2 jug jug.png
kat3 lkj lkj.png
kat3 tfh tfh.png
kat4 fsg fsg.png
kat4 gzt gzt.png
构建一个数组,如:
$table= array(
array("Product" => "Kat1","Nr" =>"abc","IMG" =>"abc.png"),
array("Product" => "Kat1","Nr" =>"xyz","IMG" =>"xyz.png"),
array("Product" => "Kat2","Nr" =>"def","IMG" =>"def.png"),
array("Product" => "Kat2","Nr" =>"gfh","IMG" =>"gfh.png"),
array("Product" => "Kat2","Nr" =>"jug","IMG" =>"jug.png"),
array("Product" => "Kat3","Nr" =>"lkj","IMG" =>"lkj.png"),
array("Product" => "Kat3","Nr" =>"tfh","IMG" =>"tfh.png"),
array("Product" => "Kat4","Nr" =>"fsg","IMG" =>"fsg.png"),
array("Product" => "Kat4","Nr" =>"gzt","IMG" =>"gzt.png"),
);
我想构建随机产品集。 每个产品组应包含每个产品组合中的一种产品。 例如以下输出:
Kat1 = abc, abc.png
Kat2 = gfh, gfh.png
Kat3 = lkj, lkj.png
Kat4 = gzt, gzt.png
我不确定我是否采用正确的方式,或者是否可能采用这种阵列。 任何想法我怎么能解决这个问题?
您可以使用此mysql查询来获得所需的结果:
SELECT
*
FROM
(SELECT
*
FROM
product
ORDER BY RAND()) AS shuffled_products
GROUP BY PRODUCT;
一旦你在php中使用循环接收到结果数组,就将其操作为所需的结果。
1)尝试在视图中重建您的阵列(按类别分组):
$tableGroupByCats = [
"Kat1" => [
["Nr" =>"abc","IMG" =>"abc.png"],
["Nr" =>"xyz","IMG" =>"xyz.png"]
],
"Kat2" => [
["Nr" =>"def","IMG" =>"def.png"],
["Nr" =>"gfh","IMG" =>"gfh.png"],
["Nr" =>"jug","IMG" =>"jug.png"]
],
"Kat3" => [
"Nr" =>"lkj","IMG" =>"lkj.png",
"Nr" =>"tfh","IMG" =>"tfh.png"
],
"Kat4" => [
["Nr" =>"fsg","IMG" =>"fsg.png"],
["Nr" =>"gzt","IMG" =>"gzt.png"]
]
];
以下代码将帮助您:
$table= array(
array("Product" => "Kat1","Nr" =>"abc","IMG" =>"abc.png"),
array("Product" => "Kat1","Nr" =>"xyz","IMG" =>"xyz.png"),
array("Product" => "Kat2","Nr" =>"def","IMG" =>"def.png"),
array("Product" => "Kat2","Nr" =>"gfh","IMG" =>"gfh.png"),
array("Product" => "Kat2","Nr" =>"jug","IMG" =>"jug.png"),
array("Product" => "Kat3","Nr" =>"lkj","IMG" =>"lkj.png"),
array("Product" => "Kat3","Nr" =>"tfh","IMG" =>"tfh.png"),
array("Product" => "Kat4","Nr" =>"fsg","IMG" =>"fsg.png"),
array("Product" => "Kat4","Nr" =>"gzt","IMG" =>"gzt.png"),
);
$tableGroupByCats = [];
foreach ($table as $product) {
$tableGroupByCats[$product['Product']][] = ["Nr" => $product["Nr"], "IMG" => $product["IMG"]];
}
或者您可以使用GROUP BY从DB中检索类似的数组
2)得到你的结果:
$result = [];
foreach ($tableGroupByCats as $ctegory => $products) {
$randNum = mt_rand(0, (count($products)-1));
$result[$ctegory] = $products[$randNum];
}
这是另一种方法:
码:
shuffle($table);
foreach($table as $row){
$result[$row["Product"]]="{$row["Product"]} = {$row["Nr"]}, {$row["IMG"]}"; // overwrite duplicates
}
ksort($result); // sort result array by Product ASC
var_export($result);
可能的输出:
array (
'Kat1' => 'Kat1 = xyz, xyz.png',
'Kat2' => 'Kat2 = jug, jug.png',
'Kat3' => 'Kat3 = lkj, lkj.png',
'Kat4' => 'Kat4 = gzt, gzt.png',
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.