簡體   English   中英

Perl腳本/ MySQL查詢可從字段的mysql數據庫查詢中計數現有數組

[英]Perl Script / MySQL query that counts existing array from mysql database query of a field

我很難解釋,但我會盡力的。

我有一個mysql表,其中包含一個名為“ inventory”的字段,該字段是一系列項目。 我需要計算該數組中不同項目的數量。 我的問題是,我在游戲中的玩家將過多的物品放入此陣列中,這會導致問題。

這是一個例子:

[[[ “NVGoggles”, “Mk_48_DZ”],[3,10]],[[ “ItemBandage”, “Skin_Sniper1_DZ”],[2,34]],[[ “DZ_Backpack_EP1”],[1]]]

該數組應計為5個項目。 在這種情況下,每個項目的數量無關緊要。 NVGoggles,Mk_48_DZ,ItemBandage,Skin_Sniper1_DZ,DZ_Backpack_EP1

空數組的示例:

[[[],[]],[[],[]],[[],[]]]

我需要腳本來:

instance_deployable中選擇清單,其中deployable_id = 16計算每行的清單陣列。 如果計數大於50個不同項目,則更新行的庫存。

我很困惑如何使用MySQL或Perl腳本來計算數組。

use strict;
use warnings;
use DBI;
use JSON 'decode_json', 'encode_json';
use List::Util 'sum';

my $limit = 50;
my $deployable_id = 16;

my $dbh = DBI->connect('DBI:mysql:database=test;host=127.0.0.1;port=3306','user','pass',{RaiseError=>1,AutoCommit=>1});
my $sth = $dbh->prepare('select distinct inventory from inventory_deployable where deployable_id=?');
$sth->execute($deployable_id);

my @bad_inventory;
while ( my ($inventory_col) = $sth->fetchrow_array ) {
    my $inventory = decode_json($inventory_col);
    if ( $limit < sum map scalar @{ $_->[0] }, @$inventory ) {
        push @bad_inventory, $inventory_col;
    }
}

$sth = $dbh->prepare('update inventory_deployable set inventory=? where inventory=? and deployable_id=?');

for my $inventory_col (@bad_inventory) {
    my $inventory = decode_json($inventory_col);
    my $keep = $limit;
    for my $category (@$inventory) {
        if ( @{ $category->[0] } > $keep ) {
            splice @{ $category->[0] }, $keep;
            splice @{ $category->[1] }, $keep;
        }
        $keep -= @{ $category->[0] };
    }
    my $new_inventory_col = encode_json($inventory);
    $sth->execute($new_inventory_col, $inventory_col, $deployable_id);
}

暫無
暫無

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

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