Jump to content

multiple separate arrays from multidimmensional?


Ageneric

Recommended Posts

I have a multidimensional array made with 3 columns and multiple rows.  I would like to make each column into its own array.

 

Example file (multidimensional array):

Col1   Col2   Col3
data   data   data
data   data   data
data   data   data
data   data   data

 

Could I do something to this extent (its just pseudocode for the most part):

for(i = 0, i < number_of_rows, i++)
$Col1 = $array[i][0];
$Col2 = $array[i][1];
$Col3 = $array[i][2];

 

Would this work? Would $Col1, $Col2, and $Col3 become arrays or just strings with the last input?  Any other better ways to do this? I am kind of new to PHP so any help would be appreciated.

Anything is possible (ish). You'll need to provide a better description of what your array looks like. try using print_r on it.

 

$array[0] = [0][0], [0][1], [0,2]
$array[1] = [1][0], [1][1], [1,2]
$array[2] = [2][0], [2][1], [2,2]
$array[3] = [3][0], [3][1], [3,2]

 

and so on. basically as you can see there are 3 columns and I would like each one of those columns a separate array.  I was thinking I could just loop through the first dimension and add it to a separate array (like in my original post), but wasnt sure if that would work.

Try using print_r on your array so we can get a picture we all understand.

 

I replaced some information to make it easier to view.  Thanks.

Array ( [0] => Array ( [0] => ID00 [1] => Name0 [2] => ssn0 ) 
[1] => Array ( [0] => ID01 [1] => Name1 [2] => ssn1 ) 
[2] => Array ( [0] => ID02 [1] => Name2 [2] => ssn2 ) 
[3] => Array ( [0] => ID03 [1] => Name3 [2] => ssn3 ) 
[4] => Array ( [0] => ID04 [1] => Name4 [2] => ssn4 ) 
[5] => Array ( [0] => ID05 [1] => Name5 [2] => ssn5 ) 
[6] => Array ( [0] => ID06 [1] => Name6 [2] => ssn6 )

To store each of these arrays within its own variable is going to require the use of variable variables. Its more efficient (and no more difficult to use) to leave the array as it is and access them from there.

 

The process would be simple though....

 

for ($i=0; $i<=count($arr)-1;$i++) {
  ${'Col' . $i} = $arr[$i];
}

 

Now, $Col1, $Col1 etc etc would be arrays. No easier to deal with than $arr[0], $arr[1] etc etc however.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.