gpt4 book ai didi

php - 尝试使用 PHP 操作数组

转载 作者:行者123 更新时间:2023-11-29 01:56:17 24 4
gpt4 key购买 nike

我不想问,但我对 PHP 还是很陌生,我被卡住了。

我在 MySQL 中存储了一个逗号分隔的列表;蓝色,12,红色,15 等我可以把它拿出来做我想做的大部分事情,但我对如何进行感到困惑。最终,我想更改数据的输出

蓝色,12,红色,15,

Blue => 12, Red => 15(没有最后一个逗号)所以我可以在我试图构建的程序中使用这些数据。

目前,我能够实现:蓝色,=> 12,=> 红色,=> 15,

代码:

$result = $con->query($sql);

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {
$id = $row['id'];
$type = $row["dataname"];
$datas = $type;
eval( "\$test = array (" . $datas . ");") ;
foreach($test as $test)
{
echo "<option name='$test'>$test , =></option>";
}
}
}

使用所需的输出,我将能够从表单输入数据以创建 SVGGraph。

提前感谢您的帮助。

最佳答案

好吧,首先,我会尝试在未来将这些信息存储在单独的行中,逗号分隔的列表适用于我们没有数据库(例如简单的文本文件)的情况。

但要回答你的问题(假设结果是分隔值的字符串):

$result = explode(',', $result);
$output = [];
for($i = 0;$i < count($result);$i=$i+2){
array_push($output, $result[i] => $result[i+1]);
}
//output:
$str = ""
foreach($output as $key => $value){
str .= $key . ' => ' . $value . ' ,';
}
$str = rtrim($str, ',');
echo $str //this will be your output

关于php - 尝试使用 PHP 操作数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27991622/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com