PHP çok boyutlu diziler hukuka

3 Cevap php

Nasıl 90 derece (devrik) PHP çok boyutlu bir dizi çevirmek istiyorsunuz? Örneğin:

// Start with this array
$foo = array(
    'a' => array(
       1 => 'a1',
       2 => 'a2',
       3 => 'a3' 
    ),
    'b' => array(
       1 => 'b1',
       2 => 'b2',
       3 => 'b3' 
    ),
    'c' => array(
       1 => 'c1',
       2 => 'c2',
       3 => 'c3' 
    )
);

$bar = flipDiagonally($foo); // Mystery function
var_dump($bar[2]);

// Desired output:
array(3) {
  ["a"]=>
  string(2) "a2"
  ["b"]=>
  string(2) "b2"
  ["c"]=>
  string(2) "c2"
}

Nasıl uygulamak istiyorsunuz flipDiagonally()?

Düzenleme: Bu ödev değildir. Ben sadece herhangi Soers en belirgin bir yoldan daha yaratıcı bir çözüm varsa görmek istiyorum. Ama birkaç insan bu sorunun çok kolay olduğu hakkında şikayet var, çünkü ne bir n th boyut dizisi ile çalışır daha genel bir çözüm hakkında?

yani nasıl bir işlev yazmak olurdu böylece:

$foo[j][k][...][x][y][z] = $bar[z][k][...][x][y][j]

? (Ben 12 iç içe for loops Bu durumda en iyi çözüm olduğunu sanmıyorum Ps..)

3 Cevap

2 döngüler ile.

function flipDiagonally($arr) {
    $out = array();
    foreach ($arr as $key => $subarr) {
    	foreach ($subarr as $subkey => $subvalue) {
    		$out[$subkey][$key] = $subvalue;
    	}
    }
    return $out;
}

Sana transpose (sütunlar satırlar sütunlar haline, satır haline) dizi atıfta düşünüyorum.

İşte sizin için yapan bir fonksiyon (source):

function array_transpose($array, $selectKey = false) {
    if (!is_array($array)) return false;
    $return = array();
    foreach($array as $key => $value) {
        if (!is_array($value)) return $array;
        if ($selectKey) {
            if (isset($value[$selectKey])) $return[] = $value[$selectKey];
        } else {
            foreach ($value as $key2 => $value2) {
                $return[$key2][$key] = $value2;
            }
        }
    }
    return $return;
}

Bir N-boyutlu bir dizi hukuka:

function transpose($array, &$out, $indices = array())
{
    if (is_array($array))
    {
    	foreach ($array as $key => $val)
    	{
    		//push onto the stack of indices
    		$temp = $indices;
    		$temp[] = $key;
    		transpose($val, $out, $temp);
    	}
    }
    else
    {
    	//go through the stack in reverse - make the new array
    	$ref = &$out;
    	foreach (array_reverse($indices) as $idx)
    		$ref = &$ref[$idx];
    	$ref = $array;
    }
}

$foo[1][2][3][3][3] = 'a';
$foo[4][5][6][5][5] = 'b';

$out = array();
transpose($foo, $out);

echo $out[3][3][3][2][1] . ' ' . $out[5][5][6][5][4];

Gerçekten hackish, ve muhtemelen en iyi çözüm, ama hey çalışıyor.

Basically it traverses the array recursively, accumulating the current indicies in an array.
Once it gets to the referenced value, it takes the "stack" of indices and reverses it, putting it into the $out array. (Is there a way of avoiding use of the $temp array?)