-4

例如:从 db 字段中检索现有数据:a,b,c,d,e 现在如此

$data= "a,b,c,d,e";

eg:要添加的新数据--- cc, gg 保存到db的最终值将是

$finaldatatobeupdatedintodb= "a,b,c,d,e,cc,gg";

检索并添加更多值。

然后将其附加回逗号列表。

如何纯粹使用 implode 和 explode 来做到这一点,而无需将其放入数组中 for 循环来重建/重新添加添加了新值的东西?

4

5 回答 5

4

If you really want to use explode and implode, you could do something like this :

First, explode the string you have :

$data= "a,b,c,d,e";
$list = explode(',', $data);
var_dump($list);

Which will give you :

array
  0 => string 'a' (length=1)
  1 => string 'b' (length=1)
  2 => string 'c' (length=1)
  3 => string 'd' (length=1)
  4 => string 'e' (length=1)

Then, add the new elements :

$to_add = array('cc', 'gg');
$new_list = array_merge($list, $to_add);
var_dump($new_list);

$new_list is now :

array
  0 => string 'a' (length=1)
  1 => string 'b' (length=1)
  2 => string 'c' (length=1)
  3 => string 'd' (length=1)
  4 => string 'e' (length=1)
  5 => string 'cc' (length=2)
  6 => string 'gg' (length=2)

And, finally, implode the $new_list, using ',' as a separator :

$output = implode(',', $new_list);
var_dump($output);

And you get :

string 'a,b,c,d,e,cc,gg' (length=15)

Of course, if you start with an array, that's one less explode to do ; and if the data you want to add is not an array, that's one more explode to do...


But, as Rob pointed out, in the simple case you are presenting, there is no need for such a complicated piece of code : strings concatenations will be more than enough ;-)

The advantage with the array/explode/implode-based solution is that you can work on the final array before imploding it into a string (say, for instance, you can sort it)

于 2009-08-10T17:48:59.577 回答
2
$finaldatatobeupdatedintodb = $data . ',cc,gg';

那是你需要的吗?很难准确理解您的问题在问什么。

于 2009-08-10T17:22:46.993 回答
1

类似于 Rob 的答案,但可能更强大一点:

$final = $data . (strlen($data) ? "," : "") . "cc,gg";

或者,如果您的额外值以数组形式出现:

$newValues = array("cc", "gg");
$final = $data . (strlen($data) ? "," : "") . implode(",", $newValues);
于 2009-08-10T18:13:43.397 回答
0
<?

function addvalues($data, $value) {

  $array = Array();
  $array = explode(",", $data);

  // if value are an array, merge it, or just add as element
  if(is_array($value))
    $array = array_merge($array, $value);
  else
    $array[] = $value;

  return implode(",", $array);
}

// original string
$data = "a,b,c,d,e";

echo "Old data = ".$data."<br>";

// see the function, it will work with both arrays and variables
$data = addvalues($data, Array("cc"));
$data = addvalues($data, "gg");

echo "New data = ".$data."<br>";

?>
于 2009-08-10T17:54:40.813 回答
0

您能否详细说明为什么需要在数据库中存储逗号分隔值?通常,您会为不同的离散值使用单独的字段。如果您有固定数量的值,则可以改用 SET 字段类型。

通常最好的解决方案是使用单独的表。维基百科关于数据库规范化的年龄可能会有所帮助。

于 2009-08-10T20:41:34.533 回答