1

i have a small issue im creating multi table and im stuck, i want to create something like this:

1 table: [4,5,6]
2 table: [7,2,7,8]
3 table: [1,1,1]
4 table: [6,0,9]

but each table can be of different size,
expected result:

[[4,7,1,6], [5,2,1,0], [6,7,1,9], [8]] 

i was trying to make it using for loop but no success so far?

array should be builded this way:
first element is collection of all t1[0] + t2[0] + t3[0] ...
second element is collection of all t1[1] + t2[1] + t3[1] ...
... and so on

4
  • php doesn't support using square bracket for array Commented Dec 27, 2012 at 12:44
  • @PankajKhairnar: Yes it does. Everyone else: Chatspeak ("u", "ur" etc.) is not welcome on SO. Commented Dec 27, 2012 at 12:46
  • 1
    @Pankaj - I suggest you reread the PHP documentation about arrays Commented Dec 27, 2012 at 12:46
  • @MarkBaker : I wasn't know php's version 5.4 and above is supporting square brackets for array. Commented Dec 27, 2012 at 13:41

2 Answers 2

4
$result = array();
foreach ([[4,5,6], [7,2,7,8], [1,1,1], [6,0,9]] as $key => $value) {
    foreach($value as $key2 => $value2) {
        $result[$key2][$key] = $value2;
    }
}

var_dump($result);
Sign up to request clarification or add additional context in comments.

2 Comments

This does have the side effect of turning the last array into an associative array with key "1" (index 0 is empty), which is not exactly the result the OP was looking for.
@Asad - that can easily be fixed by doing $result = array_map('array_values', $result); but it depends how critical the keys are as to whether this is actually needed
0
$result = array();
foreach (array(array(4,5,6), array(7,2,7,8), array(1,1,1), array(6,0,9)) as $k1 => $v1) {
    foreach($v1 as $k2 => $v2){
        if(!isset($result[$k2])){
            $result[$k2] = array();
        }
        $result[$k2][] = $v2;
    }
}

//output: [[4,7,1,6],[5,2,1,0],[6,7,1,9],[8]]

Here is a demonstration: http://codepad.org/lxJt4zOp

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.