tags:

views:

169

answers:

3

How can I "reorder" the keys in a multi-array? For example, I have:

$arr["abc"][0] = "val1";
$arr["abc"][1] = "val2";
$arr["abc"][2] = "val3";
$arr["xyz"][0] = "val4";
$arr["xyz"][1] = "val5";
$arr["xyz"][2] = "val6";

And I want it to be:

$arr[0]["abc"] = "val1";
$arr[0]["xyz"] = "val4";
$arr[1]["abc"] = "val2";
$arr[1]["xyz"] = "val5";
$arr[2]["abc"] = "val3";
$arr[2]["xyz"] = "val6";

My current effort is:

foreach ($arr as $param => $num) foreach ($num as $val) $newArr[$num][$param] = $val;

but it doesn't seem to be working. Any help would be appreciated.

EDIT: Specifically, I'm trying to loop through all elements submitted on $_FILES, as they all need the same thing done to them. By default, when there is more than one <input type="file" name="filedata[]" /> in a form, they go to $_FILES["filedata"]["name"][$index]. ("name" or any other parameter), so I cant just loop through every $_FILES["filedata"] to get at everything; thus, I need the keys of $_FILES["filedata"] reversed.

+4  A: 

I think you need to still grab the keys in the second foreach. Try something like:

foreach($arr as $k1 => $v1) {
  foreach ($v1 as $k2 => $v2) {
    $newArray[$k2][$k1] = $v2
  }
}
Peter
Whoops, I'm an idiot. I totally didn't even look at the result array he wanted.
Paolo Bergantino
A: 

It sounds like what you might be looking for is array_flip. See here:

http://us3.php.net/manual/en/function.array-flip.php

byte
I'm not sure that would work, note that the documentation for that function states that the "values of trans need to be valid keys, i.e. they need to be either integer or string", in this case the poster wants to switch the keys in a 2D array.Using array_flip for a 2D array would not work because the value of each element in the outer array is an array itself, not a string or integer.
Peter
+1  A: 

Straightforward enough with two foreach loops:

// Original version:
$arr = array();
$arr["abc"][0] = "val1";
$arr["abc"][1] = "val2";
$arr["abc"][2] = "val3";
$arr["xyz"][0] = "val4";
$arr["xyz"][1] = "val5";
$arr["xyz"][2] = "val6";

print_r($arr);

$newarray = array();
// Swap around the keys
foreach ($arr as $key1 => $val1) {
    foreach ($val1 as $key2 => $val2) {
     $newarray[$key2][$key1] = $val2;  
    }
}
print_r($newarray);

Here's the display:

// Display of $arr:
//Array
//(
//    [abc] => Array
//        (
//            [0] => val1
//            [1] => val2
//            [2] => val3
//        )
//
//    [xyz] => Array
//        (
//            [0] => val4
//            [1] => val5
//            [2] => val6
//        )
//
//)



//Display of $newarray:
//Array
//(
//    [0] => Array
//        (
//            [abc] => val1
//            [xyz] => val4
//        )
//
//    [1] => Array
//        (
//            [abc] => val2
//            [xyz] => val5
//        )
//
//    [2] => Array
//        (
//            [abc] => val3
//            [xyz] => val6
//        )
//
//)
artlung