-1

我有这种格式的mysql字符串

1.name.2.name,3.name.8.name

我有这个

$arr=split(",",$str);$count=count($arr);

这将创建 2 个数组,但我想逐项编写

for ($i=0;$i<$count;$i++){
echo $arr[$i];
// when $i=0 here must be 1 name 2 name and when $i=1 3 name 8 name
}

这仍然是正确的,但现在我想在循环内部写入值$arr[$i],我需要将它们按点分割。是否可以?

4

3 回答 3

3

你不需要任何循环

$string = "1.name.2.name,3.name.8.name";
$array = explode(",", $string);
var_dump($array);

输出

array (size=2)
  0 => string '1.name.2.name' (length=13)
  1 => string '3.name.8.name' (length=13)

如果你想进一步打破它

$array = array_map(function($v){return explode(".", $v); },$array);
var_dump($array);

输出

array (size=2)
  0 => 
    array (size=4)
      0 => string '1' (length=1)
      1 => string 'name' (length=4)
      2 => string '2' (length=1)
      3 => string 'name' (length=4)
  1 => 
    array (size=4)
      0 => string '3' (length=1)
      1 => string 'name' (length=4)
      2 => string '8' (length=1)
      3 => string 'name' (length=4)
于 2012-11-26T17:33:01.007 回答
0

使用explode()拆分,str_replace()删除.

$string = "1.name.2.name,3.name.8.name";
$arr = explode(",", $string);

for ($i=0;$i<count($arr);$i++){
echo str_replace("."," ",$arr[$i]);}
于 2012-11-26T17:39:45.057 回答
0

使用正则表达式的替代方法:

$string = "1.name.2.name,3.name.8.name";

preg_match_all('|(\d+)\.([^.,]+)[,.]?|', $string, $matches);
$matches = array_combine($matches[1], $matches[2]);

print_r($matches);

输出:

Array
(
    [1] => name
    [2] => name
    [3] => name
    [8] => name
)
于 2012-11-26T17:53:58.210 回答