在PHP中简化数组

时间:2014-04-03 11:51:30

标签: php arrays function output

我有以下需要在PHP中定义的数组,我已经以非常基本的方式完成了这些:

$ch1 = array("A-MTP-1-1","A-MTP-1-2","A-MTP-1-3","A-MTP-1-4"); 
$ch2 = array("A-MTP-1-5","A-MTP-1-6","A-MTP-1-7","A-MTP-1-8"); 
$ch3 = array("A-MTP-1-9","A-MTP-1-10","A-MTP-1-11","A-MTP-1-12");

$ch4 = array("A-MTP-2-1","A-MTP-2-2","A-MTP-2-3","A-MTP-2-4"); 
$ch5 = array("A-MTP-2-5","A-MTP-2-6","A-MTP-2-7","A-MTP-2-8"); 
$ch6 = array("A-MTP-2-9","A-MTP-2-10","A-MTP-2-11","A-MTP-2-12");

$ch7 = array("A-MTP-3-1","A-MTP-3-2","A-MTP-3-3","A-MTP-3-4"); 
$ch8 = array("A-MTP-3-5","A-MTP-3-6","A-MTP-3-7","A-MTP-3-8"); 
$ch9 = array("A-MTP-3-9","A-MTP-3-10","A-MTP-3-11","A-MTP-3-12");

但是我认为必须有一种简单的方法来编写它而不是写出每一个但不知道从哪里开始,是否有人能够指出我正确的方向来简化这个PHP,因为我也将重复对于上述情况,但每个都用B而不是A.

1 个答案:

答案 0 :(得分:10)

使用range()array_chunkextract完成此操作

<?php

for ($i = 1; $i <= 3; $i++) {           # Pass 3 as you need three sets
    foreach (range(1, 12) as $val) {    # 1,12 again as per your requirements
        $arr[] = "A-MTP-$i-" . $val;

    }
}
foreach (array_chunk($arr, 4) as $k => $arr1) {    # Loop the array chunks and set a key
    $finarray["ch" . ($k + 1)] = $arr1;
}
extract($finarray);   # Use the extract on that array so you can access each array separately
print_r($ch9);        # For printing the $ch9 as you requested.

Demo

OUTPUT : (仅适用于$ch9部分的插图)

Array
(
    [0] => A-MTP-3-9
    [1] => A-MTP-3-10
    [2] => A-MTP-3-11
    [3] => A-MTP-3-12
)

执行此操作后,您可以使用array_chunk将数组拆分为4的长度。