1

我在 mysql 表中有 2 行。有些数据跨行重复,有些数据在同一行中重复。我想呼应每个独特的价值。

数组如下所示:

Array ( [0] => Array ( [Character1] => Moe Szyslak [Character2] => 0 ) [1] => Array ( [Character1] => Homer Simpson [Character2] => 0 ) [2] => Array ( [Character1] => Homer  Simpson [Character2] => ) [3] => Array ( [Character1] => Homer Simpson [Character2] => Marge Simpson ) 

尝试了各种事情,foreach's结合 array_unique 等,但没有什么是接近的,所以我想我一定要离开了。预期结果是: Moe Szyslak Homer Simpson Marge Simpson

编辑:查询在 CI 模型中(是的,我的数据库结构应该更好):

function getCharacter()
{
$query = $this->db->query("SELECT DISTINCT Character1, Character2 FROM clip");
return $query->result_array();
}
4

2 回答 2

1

你能从你的表中做一个“选择不同的*”来删除欺骗吗?

另一种选择是检查数组中的前一个值:

for ($i = 0; $i < count($array); $i++)
{
    if ($i == 0 || $array[$i]->Character1 != $array[$i - 1]->Character1)
    {
        echo $array[$i]->Character1 ."<br />";
    }
}
于 2012-10-02T02:18:22.353 回答
1

使用DISTINCT Character1, Character2只会清除包含相同Character1和的行Character2。因此,对于以下数据,将返回三行 - 第 2 行、第 4 行和(第 1 行和第 3 行)之一

Character1    | Character2
-----------------------------
Moe Szyslak   | Homer Simpson 
Marge Simpson | Moe Szyslak 
Moe Szyslak   | Homer Simpson 
Moe Szyslak   | Marge Simpson 

使用以下代码获取唯一值

$charaters = array();
foreach ($charater_arr as $charater_arr) {
  if (!in_array($charater_arr['Character1'], $charaters)) {
    $charaters[]  = $charater_arr['Character1'];
  }
  if (!in_array($charater_arr['Character1'], $charaters)) {
    $charaters[]  = $charater_arr['Character2'];
  }
}
print_r($charaters);

否则请尝试以下查询。

SELECT Character1 AS character FROM clip 
UNION
SELECT Character2 AS character FROM clip 
于 2012-10-02T05:09:56.747 回答