尝试使用 PHP 操作数组


Trying to manipulate an array with PHP

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

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

Blue, 12, Red, 15,

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

目前,我能够实现: Blue, => 12, => Red, => 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

使用eval是最糟糕的。

以下是我在尽可能保留代码的同时如何做到这一点:

$result = $con->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $id                 = $row['id'];
        $type               = $row["dataname"];
        $datas = $type;
        $res = array();
        $arr = explode(",", str_replace(" ","",$datas));
        for ($i = 0; $i < count($arr); $i+=2) {            
            $res[$arr[$i]] = $arr[$i + 1];
        }
        foreach($res as $key=>$value)
        {
            echo "<option name='$value'>$key , =></option>";
        }
    }
}

首先,尽量不要使用 eval - 这很危险:)

其次,尝试将您需要的所有数据放入一个大字符串中。然后,您可以使用爆炸 PHP 函数将字符串转换为单个元素。您要做的最后一件事是简单地迭代数组,并将第一项作为键分配,将第二项作为元素分配到另一个数组中。

我将把实际的实现留给你,作为你的PHP编码技能的练习:)

//trim comma from the right
$str = rtrim('Blue, 12, Red, 15,', ',');
//create a helper array
$array = explode(', ', $str);
//arrange elements in the new array
for ($i = 0; $i < count($array) - 1; $i = $i + 2) {
    $new[] = $array[$i] . ' => ' . $array[$i + 1];
}
//output new elements
echo implode(', ', $new);

请不要使用eval。你几乎总是可以避免它,而且很危险。这是一个无需 eval 即可工作的解决方案:

$result = $con->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $id = $row['id'];
        $type = $row["dataname"];  // Thats our comma-seperated list, right?
        $arr = explode(',', $type); // Make $type to array
        array_pop($arr); // Delete last element because its empty
        // We go through the array with step = 2
        // because the first is always the key and the second the value
        for($i = 0; $i < count($arr); $i += 2) 
        {
             echo "<option name='$arr[$i+1]'>$arr[$i] , =></option>";
        }
    }
}

为什么 eval 是邪恶的:字符串中的任何内容都将作为脚本中的代码进行评估,具有脚本具有的所有权限,包括文件访问等。由于 eval 的字符串来自数据库,您甚至无法绝对确定在使用 eval 时执行的代码不是错误代码。此外,在调试方面,eval 很糟糕。最后:为什么要用可以避免的东西产生开销?由于所有这些原因,在使用 eval 时,它通常被认为是不好的风格。最好你永远不习惯它

如果我理解正确,你从一个字符串到一个数组再到一个字符串。如果是这样,则可以使用正则表达式跳过数组。根据字符串的长度,创建一个巨大的数组可能是一个问题。

所以我想出了这些例子:

$input = "Blue, 1, Red, 2, Green, 3, Violet, 4,";
// Output: Blue => 1, Red => 2, Green => 3, Violet => 4
echo rtrim(preg_replace('/(([^,]*),([^,]*)),+/', ''2 =>'3,', $input), ',');
// Output <option name="Blue">Blue => 1</option><option name="Red">Red => 2</option><option name="Green">Green => 3</option><option name="Violet">Violet => 4</option>
echo preg_replace('/('s*([^,]*)'s*,'s*([^,]*)'s*),+/', '<option name="'2">'2 => '3</option>', $input);

如您所见,不涉及循环。

我希望它有所帮助

编辑

这是可视化正则表达式的链接

  • 第一个正则表达式
  • 第二个正则表达式