我在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();
}
答案 0 :(得分:1)
你可以从表中选择“select distinct *”来删除欺骗吗?
另一种选择是检查数组中的前一个值:
for ($i = 0; $i < count($array); $i++)
{
if ($i == 0 || $array[$i]->Character1 != $array[$i - 1]->Character1)
{
echo $array[$i]->Character1 ."<br />";
}
}
答案 1 :(得分:1)
使用DISTINCT Character1, Character2
只会清除包含相同Character1
和Character2
的行。因此,对于以下数据,将返回三行 - 第2行,第4行和第1行(第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