I need help for my program. All I looking for is creating an array based on id_comment (id in mySQL table) then store it into another array
Example : mySQL table
id | id_comment | weight
1 | 1 | 0.311925
2 | 1 | 1
3 | 1 | 0.122169
4 | 2 | 1
5 | 3 | 1
Expected array ouput :
array(
[0]=>(0.311925, 1, 0.122169)
[1]=>(1)
[2]=>(1)
)
I've try to figure it out, but still can't make it work Here's my code (the output is not as I expect):
$id = 5;
$arrayVector = array();
for ($i=1; $i <= $id; $i++) {
$a= mysqli_query($db, "SELECT weight FROM data_latih_model WHERE id_comment='$i'")or die("Error : ".mysqli_error($db));
while ($b=mysqli_fetch_assoc($a)) {
$arrayVector[] = array('key'=>$i,'value'=>$b['weight']);
}
}
print_r($arrayVector);
Thank you for help.
You can use GROUP_CONCAT()
in MySQL to fetch all the weights where the id is the same, and put that into a string separated by a given separator. Then, to reduce redundancy, instead of running the query inside a loop, run it once, with a BETWEEN
clause.
$id = 5;
$vector = array();
$kelas = array();
$arrayVector = array();
$a = mysqli_query($db, "SELECT id_comment, GROUP_CONCAT(`weight`, SEPARATOR ', ') as weight_grouped, kelas FROM data_latih_model WHERE id_comment BETWEEN 1 AND $i")or die("Error : ".mysqli_error($db));
while ($b = mysqli_fetch_assoc($a)) {
$arrayVector[] = array($b['id_comment'] => $b['weight_grouped']);
$kelas[] = $b['kelas'];
}
change
$arrayVector[] = array('key'=>$i,'value'=>$b['weight']);
To
$arrayVector[$i][] = $b['weight'];
That should solve your problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.