PHP数组索引/拼接

时间:2016-10-20 05:14:33

标签: php arrays array-splice

我正在使用PHP 5.4(并且我不能升级到更新的东西)。我正在尝试在数组中找到元素的索引,但我很确定我做错了,因为当我调用array_splice()时,我得到一个非法的字符串偏移错误。

我正在运行SQL查询,然后将每一行推送到数组上。然后我试图找到行的属性之一的索引。当我不使用array_splice并且我只是按下行时我没有错误当我打印出每个数组条目的特定属性时。

编辑:

的print_r(阵列[I]):

Array ( [comment_id] => 0 [reply_to] => 0 [username] => user0 [comment] => comment0 )

我想找到comment_id等于某个值的位置,然后在数组[i + 1]处插入新记录。

相关的PHP代码段:

$comment_array = array();
if($result->num_rows > 0) {
   while($row = $result->fetch_assoc()){
       $new_sql = "SELECT * FROM comments WHERE reply_to = " . $row["comment_id"] . " AND reply_to != comment_id";
       $new_result = $conn->query($new_sql);
       //array_push($comment_array, $row);
       if ($new_result->num_rows > 0) {
          if($row["reply_to"] >= $row["comment_id"]){
              array_push($comment_array, $row);
          }
                                              
          while($new_row = $new_result->fetch_assoc()) {
              $index = -1; 
              foreach($comment_array as $key => $val){
                  if ($val['comment_id'] == $new_row["reply_to"]) {
                    $index = $key;
                    break;
                  }
              }
              if($index > -1){
                  array_splice($comment_array, $index, 0, $new_row);
              } else {
                  array_push($comment_array, $new_row);
              }
           }
       } else if($row["reply_to"] == $row["comment_id"]){ 
           array_push($comment_array, $row);
       }
   }
}

0 个答案:

没有答案