在PHP中用对和没有对切片数组

时间:2014-02-14 07:02:20

标签: php slice

数组值为:

$input_array = array( "Student_1","Student_2","Student_3","Student_4","student_5","Student_6","Student_7","Student_8" );

现在,我需要输出为:

$array = array( array('Student_1', 'Student_2'), array('Student_3', 'Student_4'),
  array('Student_5', 'Student_6'),  array('Student_7'),  array('Student_8') );

2 个答案:

答案 0 :(得分:0)

由于你没有指定你的格式或输出规则,我只是自己为这种情况假设规则。

我假设你希望你的数组从第一个中取出两个输入并将它们配对

  

数组(' Student_1',' Student_2'),

但最后两个没有配对

  

数组(' Student_7'),数组(' Student_8')

所以我假设你想要最后两个是分开的。 现在为解决方案

注意:这仅适用于偶数阵列。现在正在制定更一般的答案。


// We make a new array which takes every two elements from the first and appends to itself
for($i=0; $i < count($input_array)-2; $i=$i+2)
{
$array_output []= array($input_array[$i], $input_array[$i+1]);  //append the teo elements
}

// Now add the final two elements to the array
$array_output []= array($input_array[count($input_array)-2]);
$array_output []= array($input_array[count($input_array)-1]);

//Output here
echo "<pre>";
print_r($array_temp);
echo "</pre>";

如果你是php的新手

$array []= "something"; // will append to the array

如果您不希望最后两个分开(假设您输错了),

更改

for($i=0; $i < count($input_array)-2; $i=$i+2)

for($i=0; $i <= count($input_array); $i=$i+2)

并删除

/*
$array_output []= array($input_array[count($input_array)-2]);
$array_output []= array($input_array[count($input_array)-1]);
*/

答案 1 :(得分:0)

$input_array = array("Student_1","Student_2","Student_3","Student_4","student_5","Student_6","Student_7","Student_8");
function sliceArray($arr, $pairs = 3){
    $rtnArr = array();
    $total = count($arr);
    if($total < ($pairs * 2)) return 'Error: Invalid number of pairs!';
    for($i=0; $i<$total; $i++){
         if(count($rtnArr) < $pairs && isset($arr[$i+1])){ $rtnArr[] = array($arr[$i], $arr[$i+1]); $i++; }
         else $rtnArr[] = array($arr[$i]);
    }

    return $rtnArr;
}

var_dump(sliceArray($input_array));

您可以更改$ pair值以获得所需的对数。