2

データベース テーブルから行を選択し、パラメーター (この場合はアイテム) に基づいて SQL ではなく PHP を使用してそれらをグループ化したいと考えています。

SQL:

Clothes table

 id  item     owner
 1   shoes     joe 
 2   pants     joe
 3   hat       joe
 4   pants     joe
 5   hat       tom

SELECT * from Clothes where owner='joe'

 1   shoes     joe 
 2   pants     joe
 3   hat       joe
 4   pants     joe

SQL の代わりに PHP を使用して結果を表示する方法を次に示します。GROUP BY item

PHP:

 1   shoes     joe 
 2   pants     joe   //count 2
 3   hat       joe

これにはPHP配列関数があると確信しています。私はよく知らないだけだと思いますか?

4

3 に答える 3

3

最も簡単な方法は、配列キーの一意性を活用することです。

$grouped = array();

while ($row = $db->fetchResult()) {  // or however you get your data
    if (isset($grouped[$row['item']])) {
        $grouped[$row['item']]['count']++;
    } else {
        $grouped[$row['item']] = $row + array('count' => 1);
    }
}
于 2012-10-29T21:40:15.717 に答える
1

データベースアクセス関数に疑似コードを使用すると、これが機能するはずです。

$sql = "SELECT * from Clothes where owner='joe'";
$res = query($sql);
$arr = array();    

while ($row = $res->fetch())
{
    $arr[] = $row['item'];
}

$arr = array_unique($arr);

これにより、「まばらな配列」が得られる可能性があることに注意してください (つまり、キーにギャップがある可能性があります)。コメントで述べたように、そのオプションがある場合は、通常、SQL でこれを行う方が適切です。それが 2 つの同様のクエリを実行することを意味する場合でも。

于 2012-10-29T21:36:03.527 に答える
0
function group($items, $field) {
    $return = array();

    foreach ($items as $item) {
        $key = $item[$field];

        if (isset($return[$key])) {
            $return[$key]['count']++;
        } else {
            $return[$key] = $item;
            $return[$key]['count'] = 1;
        }
    }

    return $return;
}

print_r(group($results, "item"));
于 2012-10-29T21:40:45.207 に答える