PHP mysql选择数组并检查值是否存在

时间:2014-01-27 13:55:40

标签: php mysql

我有这个MySQL表:

tab

我希望得到每个平台的数量(windows,linux,mac,unknown)。

请注意,表格中没有macunknown数据,其中num将为0

条件:

  • 订单必须与想要的输出相似
  • 检查平台是否在表格中,如果没有为输出添加零

问题:如何在查询中排序以获得所需输出中的顺序,如果表中没有平台则添加零?

通缉输出:

array (
    '0' => array('name' => 'windows', 'num' => 3),
    '1' => array('name' => 'linux', 'num' => 3),
    '2' => array('name' => 'mac', 'num' => 0),
    '3' => array('name' => 'unknown', 'num' => 0)
);

我的尝试:

PHP:

function get_platforms() {
    $query = "
            SELECT platform, COUNT(platform) AS num 
            FROM stats 
            GROUP BY platform 
            ORDER BY platform ASC
            ";
    $select = mysqli_query($this->c, $query);
    while ($row = mysqli_fetch_array($select)) {
        $data[] = array(
            'name' => $row['platform'],
            'num' => $row['num']
        );
    }
    return $data;
}

当前出局:

array (
    '0' => array ('name' => 'linux', 'num' => 3)
    '1' => array ('name' => 'windows', 'num' => 3)
);

3 个答案:

答案 0 :(得分:4)

因为您的数据库中没有任何mac或未知数据,所以你不会得到任何结果,甚至不是0.你可以做的是拥有一个预配置的数组,其中包含你期望得到的平台:

$data = array(
   'windows' => 0, 
   'linux' => 0,
   'mac' => 0,
   'unknown' => 0
)

现在在get_platforms函数中执行此操作:

function get_platforms() {
    $query = "
            SELECT platform, COUNT(platform) AS num 
            FROM stats 
            GROUP BY platform 
            ORDER BY platform ASC
            ";
    $select = mysqli_query($this->c, $query);
    while ($row = mysqli_fetch_array($select)) {
        $data[$row['platform']] = $row['num'];
    }
    return $data;
}

你最终会得到这个:

$data = array(
   'windows' => 3, 
   'linux' => 3,
   'mac' => 0,
   'unknown' => 0
)

然后您可以按照您想要的方式重新格式化数据。例如,您可以这样做:

$result = array();
foreach($data as $platform => $count){
    $result[] = array('name' => $platform, 'count' => $count);
}

您最终会得到与您要求的格式相同的结果。

答案 1 :(得分:2)

首先,您应该定义所需输出的顺序,假设您有数组

$osList = array('linux', 'windows', 'mac', 'something');

现在将mysql结果提取到临时关联数组:

$data = array();
$query = "SELECT platform, COUNT(platform) AS num"
    . " FROM stats"
    . " GROUP BY platform";
$result = mysqli_query($this->c, $query);
while ($row = mysqli_fetch_array($result)) {
    $data[$row['platform']] = (int) $row['num'];        
}

在这里你可以形成输出数组:

$output = array();
foreach ($osList as $os) {
    $output[] = array(
        'name' => $os,
        'count' => isset($data[$os]) ? $data[$os] : 0
    );
}

答案 2 :(得分:2)

您必须拥有另一个表,其中列出了所有平台。例如,我们将其称为platforms,其中列platform_name具有所有唯一的平台名称(包括mac),然后查询将为:

SELECT platforms.`platform_name`, COUNT(stats.`platform`) FROM `platforms`
LEFT JOIN `stats` ON  platforms.`platform_name` = stats.`platform`
GROUP BY platforms.`platform_name`