I asked a question here, so many thanks to Gordon Linoff for his complete answer on SQL section of it.
我在这里问了一个问题,非常感谢Gordon Linoff对SQL部分的完整答案。
Problem
I have a sql table ( with PRIMARY KEY = [ ip & id ] ) , like this:
我有一个sql表(使用PRIMARY KEY = [ip&id]),如下所示:
ip | id | visits
and I want to generate a php array from that table, like this:
我想从该表生成一个php数组,如下所示:
product_rating_for_ip = array(
ip=>array(
id=>rating, id=>rating, ...
),
ip=>array(
id=>rating, id=>rating, ...
),
.
.
.
);
for example:
product_rating_for_ip = array(
"78.125.15.92"=>array(
1=>0.8,2=>0.2,3=>1.0
),
"163.56.75.112"=>array(
1=>0.1,2=>0.3,3=>0.5,8=>0.1,12=>1.0
),
.
.
.
);
Gordon Linoff suggested this SQL query which works fine:
Gordon Linoff建议这个SQL查询工作正常:
SQL Query
select v.ip, group_concat(concat(v.id, ':', v.visits / iv.maxvisits)) as ratings
from visit v join
(SELECT ip, id, visits, max(visits) as maxvisits
FROM visit
GROUP BY ip
) iv
on v.ip = iv.ip
group by v.ip;
which produces this:
产生这个:
+-------------+--------------------------+
|ip |ratings |
+-------------+--------------------------+
|154.18.72.15 |2:0.1667,1:1.0000,3:0.1667|
|162.16.18.22 |1:1.0000,3:0.3750,2:0.1250|
|142.128.1.14 |2:1.0000,1:0.2500,3:0.5000|
|78.15.92.131 |1:0.1429,3:1.0000,2:0.2857|
+-------------+--------------------------+
Question in summary
How can I put this result set into this PHP array?
如何将此结果集放入此PHP数组中?
product_rating_for_ip = array(
ip=>array(
id=>rating, id=>rating, ...
),
ip=>array(
id=>rating, id=>rating, ...
),
.
.
.
);
My problematic answer
I think I should do as this (may be incorrect or inefficient):
我想我应该这样做(可能不正确或效率低下):
$stmt = mysqli_prepare($con, "select ...");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt,$ip,$ratings);
while (mysqli_stmt_fetch($stmt)){
$value_array = explode(",",$ratings);
product_rating_for_ip = array_fill_keys($ip, $value_array);
}
1 个解决方案
#1
2
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt,$ip,$ratings);
$product_rating_for_ip = array();
while (mysqli_stmt_fetch($stmt)){
$value_array = explode(",",$ratings);
foreach ($value_array as $key => $value){
$parts = explode(':', $value);
$product_rating_for_ip[$ip][$parts[0]] = $parts[1];
}
}
#1
2
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt,$ip,$ratings);
$product_rating_for_ip = array();
while (mysqli_stmt_fetch($stmt)){
$value_array = explode(",",$ratings);
foreach ($value_array as $key => $value){
$parts = explode(':', $value);
$product_rating_for_ip[$ip][$parts[0]] = $parts[1];
}
}