繁体   English   中英

PHP-合并来自同一二维数组的2个元素

[英]PHP - Combine 2 elements from the same 2 dimensional array

我有一个数组,想将两个元素合并为一个,但是我的问题是我不知道逻辑如何工作。 这是我的代码:

  1. 查询从MySQL数据库数据来自哪里)中检索数据:

     $Retrieve_Answers = "SELECT * FROM Answers"; $Result_Answers = mysqli_query($Connection, $Retrieve_Answers); 
  2. 声明数组存储数据:

    $points = array();

  3. 从MySQL数据库中检索数据的过程

    if(mysqli_num_rows($Result_Answers) > 0){ while($Retrieved_Data = mysqli_fetch_assoc($Result_Answers)){ $points[] = $Retrieved_Data; } }

  4. 打印$ 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]。

问题:如何实现该目标? 这样做的逻辑是什么?

PS我正在为我的KMeans聚类算法这样做。

有两种解决方案可实现您的预​​期结果。

1.如果您希望立即显示这些值

第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 ",";
  }
}
?>

2.如果期望以该格式存储值以执行其他操作,请进行以下更改

步骤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) . ']';
}
?>

在不背离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);
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM