簡體   English   中英

使用array_unique()函數刪除重復的MYSQLI記錄,而無需依賴SQL來執行此操作

[英]Using the array_unique() function to remove the duplicated MYSQLI records without relying on SQL to do that

我知道這是一個奇怪的問題,但是出於個人原因我需要這樣做,所以我將MYSQLI記錄轉換為數組,但是我想在包含MYSQLI的數組上使用PHP array_unique()函數

記錄以刪除該數組中的所有重復值,而無需依賴任何SQL命令來刪除重復的記錄。

我做了很多次嘗試,但是失敗了很多次。 下面的代碼示例沒有錯誤,因為我刪除了失敗的嘗試。

這是我的代碼

<?php

$db_servername_1='localhost';
$db_username_1= 'jd';
$db_password_1= '1234';
$db_name_1= 'test';

$db_connect_1= new mysqli($db_servername_1,$db_username_1,$db_password_1,$db_name_1);

$db_query_1= "SELECT*FROM records ORDER BY id DESC LIMIT 4";

$db_result_1= $db_connect_1->query($db_query_1);

while($db_row_1= $db_result_1->fetch_assoc()){
    $items[] = $db_row_1;
}

$items = array_reverse($items ,true);

foreach($items as $item){ ?>

<h1><?php echo $item['id']; ?></h1> 

<?php 

} 

?>

這是輸出101,102,103,103。

如果我找到方法可以做到這一點,那么數組輸出將看起來像是101,102,103,那么我該怎么做呢?

這里有兩個選項供您選擇。

首先,如果您顯示的是$items數組的全部操作,則僅將ID存儲在其中,然后array_unique將為您工作:

while($db_row_1= $db_result_1->fetch_assoc()){
    $items[] = $db_row_1['id'];
}

$items = array_reverse(array_unique($items));

如果繼續使用$items進行其他操作,則僅將唯一項放入該數組中:

while($db_row_1= $db_result_1->fetch_assoc()){
    if (!array_key_exists($db_row_1['id'], $items)) {
        $items[$db_row_1['id']] = $db_row_1;
    }
}

嘗試這個:

<?php

$query = "your query here";
$resultset = $db_connect_1->query($query);
$data_array = array();
while($current = $resultset->fetch_array()){
  array_push($data_array, $current['id']);
}

$non_duplicates_array = array_unique($data_array);
foreach ($non_duplicates_array as $current_id) {
  echo $current_id;
}

array_columnarray_unique結合使用可獲得唯一的ID。

$items =
[
  ['id' =>  1, 'text' => 'foo'],
  ['id' => 10, 'text' => 'bar'],
  ['id' => 10, 'text' => 'bar2'],
  ['id' =>  3, 'text' => 'baz'],
];

foreach(array_unique(array_column($items, 'id')) as $k=>$id)
  echo $id, ' => ', $items[$k]['text'], PHP_EOL
;

輸出

1 => foo
10 => bar
3 => baz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM