我知道Stack Overflow上有很多类似的线程,但是在我的情况下它们都不起作用。
我的目标是从数据库中获得独特的节目类型。它们以逗号分隔存储(1、2、3或更多)在show_genres列中。
$link = mysqli_connect('127.0.0.1', 'root', 'pw', 'db');
$query = "SELECT show_genres FROM tv_shows";
$result = mysqli_query($link, $query);
foreach ($result as $value) {
$sh_genres = $value['show_genres'];
$sh_genres_array = array_map('trim', explode(',',$sh_genres));
// $doesnt_work = call_user_func_array("array_merge",
$sh_genres_array); // doesn't work for me
echo '<pre>' . var_export($sh_genres_array, true) . '</pre>';
}
我的结果如下:
array (
0 => 'Drama',
1 => 'Action',
2 => 'Crime',
)
array (
0 => 'Drama',
1 => 'Crime',
)
array (
0 => 'Drama',
1 => 'Thriller',
)
array (
0 => 'DIY',
)
array (
0 => 'Drama',
1 => 'Mystery',
2 => 'Supernatural',
)
但是,我只需要一个包含唯一值的数组,例如:
array (
0 => 'Drama',
1 => 'Mystery',
2 => 'Supernatural',
4 => 'Thriller',
5 => 'DIY',
6 => 'Crime',
7 => 'etc...'
)
如果我尝试在foreach循环之前创建一些数组,然后将数据存储到其中,则这种方法也不会给出结果。
也许,有一种更简单的SQL解决方案!?!!?
答案 0 :(得分:4)
请尝试使用此代码
在SQL中
$ query =“从tv_shows GROUP BY show_genres中选择show_genres”;
在PHP中
$newArray = array();
foreach ($result as $value) {
$sh_genres = $value['show_genres'];
$sh_genres_array = array_map('trim', explode(',',$sh_genres));
$newArray = array_merge($newArray , $sh_genres_array );
}
$newUniqueArray = array_unique($newArray);
答案 1 :(得分:2)
尝试使用此代码
SELECT *
FROM t AS o
INNER JOIN t AS i ON o.User = i.User AND o.Time < i.Time -- join logouts with potential logins
LEFT JOIN t AS x ON o.User = x.User AND o.Time < x.Time AND x.Time < i.Time -- any row present between logout and login
WHERE o.Event = 'LOGOUT' AND i.Event = 'LOGIN' AND x.ID IS NULL AND TIMEDIFF(i.Time, o.Time) > '00:20:00'
更新
请考虑规范化数据库
答案 2 :(得分:0)
不确定,请尝试一下。
$genre_arr = RecursiveIteratorIterator(new RecursiveArrayIterator($sh_genres_array));
$unique_genre = array_unique($genre_arr);