我有一个数组,我想将这两个元素合二为一,但我的问题是我不知道逻辑是如何工作的。这是我的代码:
查询从MySQL数据库中检索数据(DATA来自哪里):
$Retrieve_Answers = "SELECT * FROM Answers";
$Result_Answers = mysqli_query($Connection, $Retrieve_Answers);
声明数据的数组存储:
$points = array();
从MySql数据库中检索数据的过程
if(mysqli_num_rows($Result_Answers) > 0){
while($Retrieved_Data = mysqli_fetch_assoc($Result_Answers)){
$points[] = $Retrieved_Data;
}
}
从$ points数组打印数据
echo "These are the $TotalDataPoints data points: ";
foreach($points as $point){
echo "[";
echo $point['Answer_Data'];
echo "], ";
}
echo "";
**输出:**
[80],[55], [86],[59],[19],[85],[41],[47],[57],[58], [76],[22],[94],[60],[13],[93],[90],[48],[52],[54],[62],[46],[88 ],[44],[85],[24],[63],[14],[51],[40],[75],[31],[86],[62],[81], [95],[47],[22],[43],[95],[71],[19],[17],[65],[69],[21],[59],[60 ],[59],[12],[15],[22],[49],[93],[56],[35],[18],[20],[39],[59], [50],[15],[10],[47],[75],[18],[13],[45],[30],[62],[95],[79],[64] ],[11],[92],[14],[94],[49],[39],[13],[60],[68],[62],[10],[74], [44],[37],[42],[97],[60],[47],[73],
目标/目标:
我想要实现的是将数组中的两个元素组合成。
例如,从输出上面的前两个元素输出是 [80],[55],对吗?我想要发生的是[80,55]。
问题:如何实现这一目标?那是什么逻辑呢?
P.S。我正在为我的KMeans群集算法执行此操作。
答案 0 :(得分:0)
有两种解决方案可以达到预期效果。
第4步
中的变化最小
<?php
// Number of elements you want to keep.
$numberOfElements = 2;
echo "These are the $TotalDataPoints data points: ";
foreach($points as $i => $point) {
if ($i % $numberOfElements === 0) {
echo "[";
}
echo $point['Answer_Data'];
if ($i % $numberOfElements === $numberOfElements - 1) {
echo "], ";
} else {
echo ",";
}
}
?>
第3步如下
<?php
// Number of elements you want to keep.
$numberOfElements = 2;
$tmp = [];
if (mysqli_num_rows($Result_Answers) > 0) {
while($Retrieved_Data = mysqli_fetch_assoc($Result_Answers)){
$tmp[] = $Retrieved_Data['Answer_Data'];
if (count($tmp) === $numberOfElements) {
$points[] = $tmp;
$tmp = [];
}
}
}
?>
第4步如下
<?php
foreach($points as $point) {
echo '[' . implode(', ', $point) . ']';
}
?>
答案 1 :(得分:0)
如果不考虑Somnath Sinha的回答,您也可以尝试使用array_chunk()方法。替换Sinha的第3步对我来说感觉更干净。
<?php
// Number of elements you want to keep.
$numberOfElements = 2;
if (mysqli_num_rows($Result_Answers) > 0) {
while($Retrieved_Data = mysqli_fetch_assoc($Result_Answers)){
$points[] = $Retrieved_Data['Answer_Data'][0];
}
}
$points = array_chunk($points,$numberofElements);
?>