mysql 截取逗号并形成新的字段,在MySQL中拆分逗号分隔的字符串以获取动态下拉列表...

这篇博客讲述了如何在PHP中处理包含逗号分隔值的种族列。作者想要将这些字符串拆分成单独的条目以便创建动态下拉列表。目前的代码将逗号分隔的字符串作为单个条目显示,而作者希望显示每个独特的民族。解决方案是通过查询数据并使用explode()函数拆分字符串,然后过滤和打印出唯一的民族值。
摘要由CSDN通过智能技术生成

Right now I am having trouble with splitting up entries in my ethnicity column that contain entries that are separated by commas for example take a look at my

Ethnicity table

I want to be able to split up these strings into individual strings so they can all be their own entries (ex: asian, chinese, catina would all be seperate entries). I don't want to make any changes to my existing table I just want to be able to seperate these strings because I am using php to create a dynamic drop down list based on what is stored in this ethnicity column:

*Category

$conn = mysqli_connect(db, root, pass, table);

// Check connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

}

$result = mysqli_query($conn,"SELECT DISTINCT restaurant_id, ethnicity FROM ethnicity");

while ($row = mysqli_fetch_assoc($result)) {

unset($restaurantID, $ethnicity);

$restaurantID = $row['restaurant_id'];

$ethnicity = $row['ethnicity'];

echo ''.$ethnicity.'';

}

?>

Right now the drop down list is including the comma separated strings and I just want it to be able to display the distinct ethnicities individually. Any suggestions?

解决方案

I'd start buy doing the query above and exploding all the ethnicities into a new array and then printing them out:

(I haven't tested syntax just used notepad, hopefully you get the idea though.)

*Category

$conn = mysqli_connect(db,root,pass,table);

// Check connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

}

$ethnicity_array = [];

$result = mysqli_query($conn,"SELECT DISTINCT restaurant_id, ethnicity FROM ethnicity");

while ($row = mysqli_fetch_assoc($result))

{

unset($restaurantID, $ethnicity);

$restaurantID = $row['restaurant_id'];

$ethnicity = $row['ethnicity'];

$split_ethnicity = explode("," $ethnicity);

foreach ($split_ethnicity as $value)

{

if (!in_array($value, $ethnicity_array))

$ethnicity_array[] = $value;

}

}

?>

foreach ($ethnicity_array as $ethnicity)

{

echo ''.$ethnicity.'';

}

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值