[英]php counting issue using array_walk
我有一些非常不同的東西,並且我編寫的array_map
代碼有問題。 我尋求幫助,有人很好地建議他在下面編寫代碼。 然而,它似乎有幾個錯誤,因為我沒有編寫它並且對array_walk
不太熟悉,我可以使用一些幫助讓它工作。
問題-而不是向我提供數據庫中每個 object 的實際計數,而是計算類型。 例如,如果 Type_2 的數量為 3,則顯示為 1,因為 Type_2 只有一列。
$bl_type = $wpdb->get_results("SELECT Type FROM mytablenamehere");
$bl_type = [
(object)['Type' => 'Type_0'],
(object)['Type' => 'Type_1'],
(object)['Type' => 'Type_1'],
(object)['Type' => 'Type_1'],
(object)['Type' => 'Type_2'],
];
$types = [
(object)['Type' => 'Type_1'],
(object)['Type' => 'Type_2'],
(object)['Type' => 'Type_3'],
(object)['Type' => 'Type_4'],
];
$counts = array_count_values(array_column($bl_type, 'Type'));
array_walk($types, function($item) use ($counts) {
$item->Frequency = $counts[$item->Type] ?? 0;
});
echo '<table id="count"><tr>';
foreach($types as $item) {
echo '<th>', $item->Type, '</th>';
}
echo '</tr><tr>';
foreach($types as $item) {
echo '<td>', $item->Frequency, '</td>';
}
echo '</tr></table>';
陣列的示例 output:
array(4) { [0]=> object(stdClass)#2657 (1) { ["Type"]=> string(8) "Type_0" } [1]=> object(stdClass)#2658 (1) { ["Type"]=> string(7) "Type_1" } [2]=> object(stdClass)#2659 (1) { ["Type"]=> string(7) "Type_1" } [3]=> object(stdClass)#2660 (1) { ["Type"]=> string(7) "Type_1" } [4]=> object(stdClass)#2661 (1) { ["Type"]=> string(8 ) "Type_2" }
使用顯示的代碼,您根本沒有使用數據庫中的數據:
$bl_type = $wpdb->get_results("SELECT Type FROM mytablenamehere");
$bl_type = [ // this assignment here is the problem
(object)['Type' => 'Type_0'],
(object)['Type' => 'Type_1'],
(object)['Type' => 'Type_1'],
(object)['Type' => 'Type_1'],
(object)['Type' => 'Type_2'],
];
第二個賦值$bl_type = [...]
會覆蓋之前保存數據庫查詢結果的變量$bl_type
的內容。 因此,無論您的數據庫存儲了什么,您總是只能得到相同的結果。
因此,只需刪除第二個分配並只保留這一行:
$bl_type = $wpdb->get_results("SELECT Type FROM mytablenamehere");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.