开发者

an better way to do this code

myarray[] = $my[$addintomtarray]  
//52 elements  
for ($k=0; $k <= 12; $k++){  
    echo  $myarray[$k].' ';  
}  
echo '<br>';   
for ($k=13; $k < 26; $k++){  
    echo  $myarray[$k].' ';  
}  
echo '<br>';   
f开发者_如何学运维or ($k=26; $k < 39; $k++){  
    echo  $myarray[$k].' ';  
}  
echo '<br>';  
for ($k=39; $k <= 51; $k++){  
    echo  $myarray[$k].' ';  
}   

how to shorten this array code...all I am doing here is splitting an array of 52 elements into 4 chunck of 13 elements each. In addition I am adding formation with br and space

thanks


Use the modulus operator (%) to know when you are at a multiple of 13:

for ($k=0; $k <= 51; $k++){  
    echo  $myarray[$k].' ';
    if (($k > 0) && (($k % 13) === 0)) {
        echo '<br>';
    }
} 


A better way to do this might be to use the array_slice function.

From the docs:

array array_slice ( array $array , int $offset [, int $length [, bool $preserve_keys = false ]] )

"array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters."


Loop through all elements in one loop. Use a % comparison conditionally.

~Edit~ See Mr. Klatchko's code below.


I came up with this this idiom just yesterday to prevent flooding by my web crawler.

$myarray[] = $my[$addintomtarray]  

// ...

// NOTE: This modifies $myarray!  Make a copy of it first if you
// need to (e.g. by making this its own function and passing by-value).

while(($line = array_splice($myarray, 0, 13))) {
    echo implode(' ', $line);

    if(count($myarray) !== 0) {
        echo '<br/>';
    }
}


I've always preferred to use array_chunk(). Once I get the array distributed in its raw form, I can display it any way I want.

array_chunk( $myarray, 13 );

Now you have a 4 element array, each element of which contains a 13 element array. A simple nested loop will allow you to iterate and display in whatever manner you choose.


You definitely don't need to do that many for loops:

$myarray[] = $my[$addintomtarray];
//52 elements

$i = 1;
foreach( $myarray as $v ){
    echo "$v ";

    if( 0 == $i % 13 )
        echo '<br />';

    $i++;
}  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜