简体   繁体   中英

PHP: Get result from arrays.

Sorry for the title. its little difficult for me to explain. I've spent almost few hours to figure this out, but failed. So I'm posting it here.

I have following array

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [1] => Array
        (
            [0] => p
            [1] => q
            [2] => r
        )

    [2] => Array
        (
            [0] => w
            [1] => x
            [2] => y
            [3] => z
        )

)

The array could have any number of elements.

What i need to do is create another array based on above array.

Array
(
    [0] => Array
        (
            [0] => a
            [1] => p
            [2] => w
        )

    [1] => Array
        (
            [0] => b
            [1] => q
            [2] => x
        )

    [2] => Array
        (
            [0] => c
            [1] => r
            [2] => y
        )

    [3] => Array
        (
            [0] => Z
        )

)

Any hints will be appreciated.

Thanks

如果您还没有使用 PHP 5.5,请升级到 PHP 5.5,然后使用array_column

If PHP < 5.5 or you don't want to use array_column-solution

$newArray = array();

foreach($array as $row)
     foreach($row as $key => $value){
         if (!isset($newArray[$key]))
             $newArray[$key] = array();
         $newArray[$key][] = $value;
     }

Just try with array_walk_recursive :

$input  = [
    ['a', 'b', 'c'],
    ['p', 'q', 'r'],
    ['w', 'x', 'y', 'z'],
];
$output = [];


array_walk_recursive($input, function($value, $index) use (&$output) {
    if (!isset($output[$index])) {
        $output[$index] = [];
    }

    $output[$index][] = $value;
});

Output:

array (size=4)
  0 => 
    array (size=3)
      0 => string 'a' (length=1)
      1 => string 'p' (length=1)
      2 => string 'w' (length=1)
  1 => 
    array (size=3)
      0 => string 'b' (length=1)
      1 => string 'q' (length=1)
      2 => string 'x' (length=1)
  2 => 
    array (size=3)
      0 => string 'c' (length=1)
      1 => string 'r' (length=1)
      2 => string 'y' (length=1)
  3 => 
    array (size=1)
      0 => string 'z' (length=1)

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