简体   繁体   中英

php array operations append element

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

$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);
$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM