0

I have a Multi dimension array and what i 'd like to do is put array to insert the element in each column

for example

Multi dimension array :

Tony 14
Peter 20

I would like to insert them into a different array , so that

column0[]={Tony, Peter}
column1[]={14, 20}

Since i do not know the actual no of column , how can i achieve this?

   for ($row = 1; $row <= $highestRow; $row++) {
        for ($y = 0; $y < $highestColumn; $y++) {
    ................what should be added here................
            }
        }

Thank you

5
  • I don't see multidimensional array in your question Commented May 7, 2012 at 4:42
  • @zerkms I think he means that the rows are one dimension, the columns are the second :) Commented May 7, 2012 at 4:43
  • @Jack: ok. But anyway I'd better go with array in php syntax, that doesn't allow different meanings in terms ;-) Commented May 7, 2012 at 4:44
  • @user782104 Where are you getting the data from? Excel sheet, CSV file, etc.? Maybe you could post a small subset of the data? Commented May 7, 2012 at 4:45
  • from spreadsheet, but is that affect ? Commented May 7, 2012 at 4:50

1 Answer 1

1

Check out the code below. All you're doing in your actual loop, is swapping the $y and the $row

<?php
$original_array = array(
    array('Tony', 14),
    array('Peter', 20)
);

print_r($original_array);

// Array
// (
//     [0] => Array
//         (
//             [0] => Tony
//             [1] => 14
//         )

//     [1] => Array
//         (
//             [0] => Peter
//             [1] => 20
//         )

// )

$new_array = array();

for ($row = 0; $row < count($original_array); $row++) {
    for ($y = 0; $y < count($original_array[0]); $y++) {
        $new_array[$y][$row] = $original_array[$row][$y];
    }
}

print_r($new_array);

// Array
// (
//     [0] => Array
//         (
//             [0] => Tony
//             [1] => Peter
//         )

//     [1] => Array
//         (
//             [0] => 14
//             [1] => 20
//         )

// )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.