duanjiu4498 2013-10-14 13:22
浏览 56

在php中拆分多维数组

i have a PHP array as follow :

$array = array("one" => "is one" , "two" => "is two" , "three" => "is three", "four" => "is four" , "five" => "is five" , "six" => "is six" , "seven" => "is seven" , "eight" => "is eight" , "nine" => "is nine" , "ten" => "is ten");

After partitioning this array into two groups that is 5 elements, using following method:

 function partition(Array $list, $p) {
    $listlen = count($list);
    $partlen = floor($listlen / $p);
    $partrem = $listlen % $p;
    $partition = array();
    $mark = 0;
    for($px = 0; $px < $p; $px ++) {
        $incr = ($px < $partrem) ? $partlen + 1 : $partlen;
        $partition[$px] = array_slice($list, $mark, $incr);
        $mark += $incr;
    }
    return $partition;
}
$partitioned = partition($array , 2);

Now to use this partitioned array i use the following code :

$totalArrays = count($partitioned);
for($pb=0; $pb < $totalArrays; $pb++){
    print_r($partitioned[$pb]);

}

The above print_r($partitioned[$pb]); outputs 2 arrays.

This displays the contents of both arrays as keys and values, what i actually wanted to achieve is that , i would like to save elements of first array into one file named "First.txt" and "Second.txt" for the second, the names doesn't matters they can be numbered but what matters is the partitions, forexample if there are 10 partitions each partition will save its element into its own file.

I have had some solutions but they ain't working as expected so i am here to request for your solutions.

Thank you.

  • 写回答

1条回答 默认 最新

  • dongshengli6384 2013-10-14 13:24
    关注

    Discover array_chunk():

    $result = array_chunk($source, 5);
    

    if you want to preserve keys, then specify third parameter:

    $result = array_chunk($source, 5, true);
    

    Edit since you need guide about writing this to files, I'll provide a hint:

    $files = ['One.txt', 'Two.txt', 'Three.txt']; //fill this as you need
    foreach(array_chunk($source, 5, true) as $i=>$partition)
    {
       //write i-th partition to file with i-th name
       writePartition($files[$i], $partition);
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100