2011-06-10 98 views

回答

1

我改變了一些東西。我沒有使用$ newA,#newB,$ newC,而是使用了$ m數組。

$a = array("a1", "a2", "a3"); 
    $b = array("b1", "b2", "b3"); 
    $c = array("c1", "c2", "c3"); 

$count = count($a); 
$i = 0; 
$m = array(); 
for($i;$i < $count; $i++) { 
     $m[] = array($a[$i], $b[$i], $c[$i]); 
} 

print_r($m); 

輸出:

Array 
(
    [0] => Array 
     (
      [0] => a1 
      [1] => b1 
      [2] => c1 
     ) 

    [1] => Array 
     (
      [0] => a2 
      [1] => b2 
      [2] => c2 
     ) 

    [2] => Array 
     (
      [0] => a3 
      [1] => b3 
      [2] => c3 
     ) 

) 
1

這個怎麼樣...

<?php 

$arr1 = array(1, 2, 3); 
$arr2 = array(1, 2, 3); 
$arr3 = array(1, 2, 3); 

function array_divide() { 
    $ret = array(); 
    foreach (func_get_args() as $array) { 
     foreach ($array as $key=>$value) { 
      $ret[$key][] = $value; 
     } 
    } 
    return $ret; 
} 

list($new1, $new2, $new3) = array_divide($arr1, $arr2, $arr3); 
var_dump($new1); 

顯然該函數可以只返回一個值,所以你需要list,如果你想獲得多個值出它。

2
function transpose(){ 
    $array = func_get_args(); 
    array_unshift($array, null); 
    return call_user_func_array('array_map', $array); 
} 

$a = array('a1', 'a2', 'a3'); 
$b = array('b1', 'b2', 'b3'); 
$c = array('c1', 'c2', 'c3'); 

list($newa, $newb, $newc) = transpose($a,$b,$c); 

var_dump($newa, $newb, $newc); 

轉置功能從here,稍微修改我。

1

這是我的出價。試圖使它儘可能地靈活:

function array_rotate(){ 
    $args = func_get_args(); 
    $argc = func_num_args(); 

    // check if all items are arrays and also get the 
    // length of the longest array 
    $maxCount = 0; 
    foreach ($args as $arg){ 
    if (!is_array($arg)) 
     throw new ArgumentException("array_rotate: All arguments must be arrays"); 
    $_count = count($arg); 
    if ($_count > $maxCount) 
     $maxCount = $_count; 
    } 

    // setup the returned result 
    $result = array_fill(0, $argc, array()); 

    // iterate over all items 
    for ($v = 0; $v < $argc; $v++){ 
    for ($h = 0; $h < $maxCount; $h++){ 
     $result[$h][$v] = isset($args[$v][$h]) ? $args[$v][$h] : null; 
    } 
    } 

    return $result; 
} 

而且用法示例:

$newAry = array_rotate(
    array('a1','a2','a3'), 
    array('b1','b2','b3'), 
    array('c1','c2','c3') 
); 

// above yields: 
Array 
(
    [0] => Array 
     (
      [0] => a1 
      [1] => b1 
      [2] => c1 
     ) 

    [1] => Array 
     (
      [0] => a2 
      [1] => b2 
      [2] => c2 
     ) 

    [2] => Array 
     (
      [0] => a3 
      [1] => b3 
      [2] => c3 
     ) 

) 

而且在不平坦的陣列的情況下,則返回null:

print_r(array_rotate(
    array('a1','a2'), 
    array('b1','b2','b3','b4'), 
    array('c1','c2','c3') 
)); 

// above yields: 
Array 
(
    [0] => Array 
     (
      [0] => a1 
      [1] => b1 
      [2] => c1 
     ) 

    [1] => Array 
     (
      [0] => a2 
      [1] => b2 
      [2] => c2 
     ) 

    [2] => Array 
     (
      [0] => 
      [1] => b3 
      [2] => c3 
     ) 

    [3] => Array 
     (
      [0] => 
      [1] => b4 
      [2] => 
     ) 
)