由于我正在使用一个相当古老的库,我需要将数组块分成五个块.所以,如果我的数组有9个元素,我需要将它组合起来(5和4)然后我需要在最后一个数组中添加一个空元素以使其达到5.
我写了一些非常糟糕的代码,但是我知道这是违反DRY原则的,因为它计算了数字,并使用多个if语句来推送正确数量的空白元素以重新获得5.
谁能告诉我如何我这样应该向下突破该代码$chunkFive被array_push编到,直到它有5个元素呢?
$blank = array("","","blank-image.png","",""); // create the blank image array
if(count($chunkFive) < 5){
echo 'it contains less than five elements';
if(count($chunkFive) == 4){
echo 'insert one element'; // 4 present + array_push 1 = 5
array_push($chunkFive,$blank);
}else if(count($chunkFive) == 3){
echo 'insert two elements'; // 3 present + array_push 2 = 5
array_push($chunkFive,$blank);
array_push($chunkFive,$blank);
}else if(count($chunkFive) == 2){
echo 'insert three elements'; // 2 present + array_push 3 = 5
array_push($chunkFive,$blank);
array_push($chunkFive,$blank);
array_push($chunkFive,$blank);
}else if(count($chunkFive) == 1){
echo 'insert four elements'; // 1 present + array_push 4 = 5
array_push($chunkFive,$blank);
array_push($chunkFive,$blank);
array_push($chunkFive,$blank);
array_push($chunkFive,$blank);
}
}else{
echo 'it contains five elements'; // no need to adjust
// do nothing
}
Run Code Online (Sandbox Code Playgroud)
用途array_pad:
array_pad($chunkFive, 5, $blank);
Run Code Online (Sandbox Code Playgroud)
例如:
[20] boris> $blank = ''; // easier to read ;-)
// ''
[21] boris> array_pad(array("one"), 5, $blank);
// array(
// 0 => 'one',
// 1 => '',
// 2 => '',
// 3 => '',
// 4 => ''
// )
[22] boris>
Run Code Online (Sandbox Code Playgroud)
该函数自php 4以来一直存在 - 使用内置函数通常是值得的,因为它们在大多数情况下都是优化的c实现.
| 归档时间: |
|
| 查看次数: |
389 次 |
| 最近记录: |