douwei1128 2014-07-10 15:27
浏览 50
已采纳

在php中单独读取字符串的元素

I am trying to import a csv file into a database, but I'm getting stuck on getting separately the elements of the string returned while reading the file.

I read the csv file like this:

if(!file_exists($fileURL) || !is_readable($fileURL)){
    return FALSE;
}

$header = null;
$data = array();

if (($handle = fopen($fileURL, 'r')) !== FALSE)
{
    while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
    {

        if($header === null){
            $header = $row;
        }
        else{
            $data[] = array_combine($header, $row);
        }
    }

    fclose($handle);
}

return $data;

Then that returns an array like this:

array(1) { ["codeA  codeB   codeC   codeD   codeE   codeF   codeG   codeH   codeI   codeJ   codeK   codeL   codeM   codeN   codeO   codeP   codeQ   codeR   codeS   codeT   codeU"]=> string(293) "6928549666338    6928549666338 6928549666338 6928549666338   6928549666338   6928549666338   6928549666338   6928549666338   6928549666338   6928549666338   6928549666338   6928549666338   6928549666338   6928549666338 6928549666338 6928549666338   6928549666338   6928549666338   6928549666338   6928549666338   6928549666338" }

When I try to separate the values, it won't happen and I don't understand why!

I try to separate them like this:

$separatedArray = array();

$keys = array_keys($arrayToSeparate);
$separatedKeys = explode(" ",$keys[0]);

$values = array_values($arrayToSeparate);
$separatedValues = explode(" ",$values[0]);



foreach($separatedKeys as $i)
{
    $key = $separatedKeys[$i];
    $separatedArray[$key] = $separatedValues[$i];
}

    return $separatedArray;

I've tried with str_getcsv, str_replace and nothing works.. I would really appreciate some help!

  • 写回答

2条回答 默认 最新

  • duanlijia5864 2014-07-10 15:30
    关注

    Change this:

    $separatedKeys = explode(" ",$keys[0]);
    

    to this:

    $separatedKeys = explode(" ",preg_replace("@[\s]+@i", ' ', $keys[0]));
    

    Do the same for the values array. Don't know why you have 2 anyways... As they both do the same.

    UPDATE:

    $separatedArray = explode(" ",preg_replace("@[\s]+@i", ' ', $arrayToSeparate[0]));
    return $separatedArray;
    

    UPDATE 2 (by using/changing your code):

    $separatedArray = array();
    
    $separatedValues = explode(" ", preg_replace("@[\s]+@i", ' ', $arrayToSeparate[0]));
    
    for ($i = 0; $i < count($separatedValues); $i++) {
        $separatedArray[$i] = $separatedValues[$i];
    }
    
    return $separatedArray;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能