0

レポートを生成する目的で、単一の配列を複数の配列に分割する必要があります。

以下に示すような配列があります。

Array
(
    [blah_1] => 1
    [blahblah_1] => 31
    [blahblahblah_1] => 25
    [blah_3] => 1
    [blahblah_3] => 3
    [blahblahblah_3] => 5
    [blah_10] => 1
    [blahblah_10] => 10
    [blahblahblah_10] => 2
)

上記を分割したいのですが、

Array
(
    [blah_1] => 1
    [blahblah_1] => 31
    [blahblahblah_1] => 25
)

Array
(
    [blah_3] => 1
    [blahblah_3] => 3
    [blahblahblah_3] => 5
)

Array
(
    [blah_10] => 1
    [blahblah_10] => 10
    [blahblahblah_10] => 2
)

PHPでこれを行うにはどうすればよいですか??

4

5 に答える 5

2
$oldarray=array('blah_1'=>1,'blahblah_1'=>31,'blahblahblah_1'=>25,
'blah_3'=>1,'blahblah_3'=>3,'blahblahblah_3'=>5,
'blah_10'=>1,'blahblah_10'=>10,'blahblahblah_10'=>2
)
$newarray=array();

foreach ($oldarray as $key=>$val) { //Loops through each element in your original array

    $parts=array_reverse(explode('_',$key)); //Splits the key around _ and reverses
    $newarray[$parts[0]][$key]=$val; //Gets the first part (the number) and adds the
    //value to a new array based on this number.

}

出力は次のようになります。

Array (
    [1]=>Array
    (
        [blah_1] => 1
        [blahblah_1] => 31
        [blahblahblah_1] => 25
    )

    [3]=>Array
    (
        [blah_3] => 1
        [blahblah_3] => 3
        [blahblahblah_3] => 5
    )

    [10]=>Array
    (
        [blah_10] => 1
        [blahblah_10] => 10
        [blahblahblah_10] => 2
    )
)
于 2012-05-29T12:15:59.837 に答える
0

array_chunkを使用します。例:

<?php
   $chunks = array_chunk($yourarray, 3);
   print_r($chunks);
?>
于 2012-05-29T12:10:25.697 に答える
0

array_chunkを使用する

すなわち

$a = array(1,2,3,4,5,6,7);
var_dump(array_chunk($a, 3));
于 2012-05-29T12:12:00.387 に答える
0

array_sliceを探しているかどうかわからない

しかし、この例を見てください:

    <?php
        $input = array("a", "b", "c", "d", "e");


       print_r(array_slice($input, 2, -1));
       print_r(array_slice($input, 2, -1, true));
?>

結果は次のようになります。

Array
(
    [0] => c
    [1] => d
)
Array
(
    [2] => c
    [3] => d
)
于 2012-05-29T12:12:22.277 に答える
-1
array_chunk ( array $input , int $size);
于 2012-05-29T12:10:52.560 に答える