【问题标题】:PHP Explode - Multiple Lines With Multi-Dimensional ArrayPHP Explode - 多行多维数组
【发布时间】:2013-10-07 20:00:20
【问题描述】:

我正在使用以下代码将我的数据数组(逗号分隔但不是来自文件)更改为可以使用的数组。我的代码如下...

public function exportPartsAuthority($fileArray)
{       
    // Do whatever - sample code for a webservice request below.
    foreach ($fileArray as $filename => $fileContent) {

        // Do nothing

    }

    foreach(explode("\n",$fileContent) as $line){
        $item=explode(",",$line);
        file_put_contents('/home/apndev/public_html/output.txt', print_r($item, true));
    }

}

$fileContent 的值如下所示...

"100000002","flatrate_flatrate","1.0000","Brian","","","","","Sunrise","33323","Florida","US","","",
"100000002","flatrate_flatrate","1.0000","Brian","","","","","Sunrise","33323","Florida","US","","",
"100000003","flatrate_flatrate","1.0000","Brian","","","","","Sunrise","33323","Florida","US","2P-225","A1",

这就是它在 $fileContent 爆炸后出现在我的文件中的方式...

Array
(
[0] => "100000002"
[1] => "flatrate_flatrate"
[2] => "1.0000"
[3] => "Brian"
[4] => ""
[5] => ""
[6] => ""
[7] => ""
[8] => "Sunrise"
[9] => "33323"
[10] => "Florida"
[11] => "US"
[12] => ""
[13] => ""
[14] => 
"100000002"
[15] => "flatrate_flatrate"
[16] => "1.0000"
[17] => "Brian"
[18] => ""
[19] => ""
[20] => ""
[21] => ""
[22] => "Sunrise"
[23] => "33323"
[24] => "Florida"
[25] => "US"
[26] => ""
[27] => ""
[28] => 
"100000003"
[29] => "flatrate_flatrate"
[30] => "1.0000"
[31] => "Brian"
[32] => ""
[33] => ""
[34] => ""
[35] => ""
[36] => "Sunrise"
[37] => "33323"
[38] => "Florida"
[39] => "US"
[40] => "2P-225"
[41] => "A1"
[42] => 
)

我将如何从该字符串中生成每一行作为自己的数组?

【问题讨论】:

  • 您的输入数据已经存在缺陷,请先修复它
  • 我隐藏了很多数据,因为它是个人信息。否则它有什么缺陷?

标签: php arrays csv


【解决方案1】:

您实际上已经很接近了,因为您已经通过调用explode() 为每一行创建了一个新数组——您只需要一个变量来保存您正在创建的所有$items,并且在循环的每次迭代中添加$item

function exportPartsAuthority($fileArray) {       

    //this would hold your output
    $arrayOfArrays = array();

    foreach ($fileArray as $filename => $fileContent) {

        // Do nothing
        foreach(explode("\n",$fileContent) as $line){
            $item=explode(",",$line);
            file_put_contents('/home/apndev/public_html/output.txt', print_r($item, true));

            //now add it to your arrayOfArrays
            $arrayOfArrays[] = $item;
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 2022-01-07
    • 2013-03-04
    • 2011-09-22
    相关资源
    最近更新 更多