使用Explode在数组中拆分值以形成多维数组

时间:2015-04-01 22:15:54

标签: php arrays multidimensional-array explode

我是PHP的新手,所以要善待。 :) 我有一个3深的阵列。像这样:

Array(5) { 
[0]=> array(5) { 

    [0]=> string(0) "" 
    [1]=> string(21) "0,245.19000000,864432"
    [2]=> string(21) "1,245.26000000,864432" 
    [3]=> string(21) "2,245.49000000,864432" 
    [4]=> string(21) "4,245.33000000,864432" 
}

[1]=> array(5) { 
    [0]=> string(0) "" 
    [1]=> string(21) "0,245.19000000,864453" 
    [2]=> string(21) "1,245.26000000,864453" 
    [3]=> string(21) "2,245.49000000,864453" 
    [4]=> string(21) "4,245.33000000,864453" 
 }
}...

我想用逗号(“2,245.49000000,864453”)爆炸内部字符串,这样数组就像这样变深4:

Array(5) { 
  [0]=> array(5) { 

    [0]=> string(0) "" 

    [1]=> array (3)
              [0]=> "0"
              [1]=> "245.19000000"
              [2]=> "864432"

    [2]=> array (3)
              [0]=> "1"
              [1]=> "245.26000000"
              [2]=> "864432"

    [3]=> array (3)
              [0]=> "3"
              [1]=> "245.49000000"
              [2]=> "864432"

    [4]=> array (3)
              [0]=> "4"
              [1]=> "245.3000000"
              [2]=> "864432"

    [4]=> array (3)
              [0]=> "5"
              [1]=> "245.3300000"
              [2]=> "864432"
 }
}
...

到目前为止,我有:

$done = array();

for ($i = 0; $i<=count($chunks); $i++) { //loops to get size of each 2d array
$r = count($chunks[$i]);

        for ($c = 0; $c<=count($chunks[$r]); $c++) { //loops through 3d array

        $arrayparts = $chunks[$i][$c];
        $done[] = explode(",", $arrayparts); //$arrayparts is 3d array string that is exploded each time through loop

    }

}

我认为这段代码应该可以工作,但是当我在var_dump上打印什么内容时? 有人可以帮我学习吗?

谢谢!

建议: $ chunks是3d数组

foreach($chunks as $innerArray) {
        $result[] = array_map(function($v){
            return explode(",", $v);
        }, $innerArray);
    }

2 个答案:

答案 0 :(得分:0)

不要让它变得复杂,只需使用它:

(这里我使用foreach循环遍历每个innerArray,然后使用array_map()遍历所有值并将其展开并将其返回到结果数组中)

<?php

    foreach($arr as $innerArray) {
        $result[] = array_map(function($v){
            return explode(",", $v);
        }, $innerArray);
    }

    print_r($result);

?>

答案 1 :(得分:0)

这使用array_map()两次。也许是一个更好的方式,但我正在喝啤酒三:

$result = array_map(function($v){
                        return array_map(function($v){ return explode(',', $v); }, $v);
                    }, $array);