开发者

array elements separated by ',',and str_replace();?

I have an source data separated by , but some cases in the its elements contains ,

$A = Array
  (
    [0] => Array
        (
            [0] => ",123, abc , company , Inc., 3043, 200, USD",// [123], [abc] , [company , Inc.], [3043], [200], [USD]
            [1] => ",456, def , company,Inc., 3043, 200, USD"
        )

  ) 

By could not change the data source.( company , Inc., is always fixed array orders )

foreach ($A as $key=>$value){

  foreach($value as $k=>$v){
       $line 开发者_StackOverflow社区 =  str_replace(',', ';', $v);
       $row = explode(',', $line);
      list($a, $b, $c, $d, $e, $f) = $row;

  }
}

EDIT:

RULE:

yes , the order of company , Inc always fixed and the number of , always 6


$array = explode(',', trim($string, ','));
while (count($array) > 6) {
  $array[3] = $array[3] . ',' . $array[4];
  unset($array[4]);
  $array = array_merge($array);
}

Just a short description: We merge the 3rd and 4th element together, as long as there are more than 6 elements.

Another a little bit more straight forward solution:

$array = explode(',', trim($string, ','));
$result = array_slice($array, 0, 2);
$result[] = implode(',', array_slice($array, 2, - 3));
$result = array_merge($result, array_slice($array, -3));


Made you a simple function that does it. The only reason I create $foo,$bar,$baz is so you can easily use foreach and keep the order.

function parse($str){
    $parts=explode(',',$str,4);
    $result=array($parts[1],$parts[2]);
    $parts=explode(',',$parts[3]);
    $foo=array_pop($parts);
    $bar=array_pop($parts);
    $baz=array_pop($parts);
    $result[2]=implode(',',$parts);
    $result[3]=$baz;
    $result[4]=$bar;
    $result[5]=$foo;
    return $result;
}


Change the source data to contain quotes around the values, e.g. change it to

 [0] => '"123", "abc" , "company , Inc.", "3043", "200", "USD"'

Then use str_getcsv.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜