Restructure multidimensional array of column data into multidimensional array of row data

眉间皱痕 提交于 2019-12-17 02:32:15

问题


I have the following associative array of column data:

$where = array(
    'id'=>array(
        12,
        13,
        14
    ),
    'date'=>array(
        '1999-06-12',
        '2000-03-21',
        '2006-09-31'
    )
);

I need to transpose / rotate the structure to be an array of rows (with merged column data assigned to their respective row). I don't need the column names in the result.

Expected output:

$comb = array(
    array(12, '1999-06-12'),
    array(13, '2000-03-21'),
    array(14, '2006-09-31')
);

回答1:


As Kris Roofe stated in his deleted answer, array_column is indeed a more elegant way. Just be sure to put it into some kind of a foreach loop, similar to what Sahil Gulati showed you. For example, like this:

$result = array();

foreach($where['id'] as $k => $v)
{
  $result[] = array_column($where, $k);
}

The var_dump output of $result is exactly what you're looking for

array(3) {
  [0]=>
  array(2) {
    [0]=>
    int(12)
    [1]=>
    string(10) "1999-06-12"
  }
  [1]=>
  array(2) {
    [0]=>
    int(13)
    [1]=>
    string(10) "2000-03-21"
  }
  [2]=>
  array(2) {
    [0]=>
    int(14)
    [1]=>
    string(10) "2006-09-31"
  }
}



回答2:


Solution 1: Hope this simple foreach to get the desired result

Try this code snippet here

<?php
ini_set('display_errors', 1);
$where = array('id'=>array(12,13,14),'date'=>array('1999-06-12','2000-03-21','2006-09-31'));

$result=array();
foreach($where["id"] as $key => $value)
{
    $result[]=array($value,$where["date"][$key]);
}

Solution 2: Here we are using array_walk to achieve the same result

Try this code snippet here

<?php
ini_set('display_errors', 1);
$result=array();
$where = array('id'=>array(12,13,14),'date'=>array('1999-06-12','2000-03-21','2006-09-31'));

array_walk($where["id"], function($value,$key) use(&$result,&$where){
    $result[]=array($value,$where["date"][$key]);
});
print_r($result);

Solution 3: Here we are using array_shift on $where["date"].

Try this code snippet here

<?php
ini_set('display_errors', 1);
$result=array();
$where = array('id'=>array(12,13,14),'date'=>array('1999-06-12','2000-03-21','2006-09-31'));

foreach($where["id"] as $value)
{   
    $result[]=array($value,  array_shift($where["date"]));
}
print_r($result);



回答3:


Wanna see a fancy trick?

(php minimum version: 5.6)

If you strip the array keys (id and date) from $where you can use a variadic function and write a nice tight little one-liner! And you don't have to bother instantiating any result arrays -- no fuss. PHP is so excellent -- big fan.

Input:

$where=['id'=>[12,13,14],'date'=>['1999-06-12','2000-03-21','2006-09-31']];

Method #1: variadic array_map() with func_get_args()

$comb=array_map(function(){return func_get_args();},...array_values($where));
var_export($comb);

This method is robust as it will handle a variable number of "rows" and "columns". Here is a demo with a few examples.


Or if you are are sub-5.6, you can use this, but it is less flexible/robust (more literal to the OP's sample data):

Method #2: array_map() with two inputs

$comb=array_map(function($v1,$v2){return [$v1,$v2];},$where['id'],$where['date']);
var_export($comb);

Output from either method:

array (
  0 => 
  array (
    0 => 12,
    1 => '1999-06-12',
  ),
  1 => 
  array (
    0 => 13,
    1 => '2000-03-21',
  ),
  2 => 
  array (
    0 => 14,
    1 => '2006-09-31',
  ),
)

I find array_map() to be my favorite function for this case because it creates the result array in the same line (as opposed to returning a true/false result like array_walk(); or using a foreach loop and printing after it is done). This means you can do a true one-liner print out without declaring a result variable...

var_export(array_map(function(){return func_get_args();},...array_values($where)));

or

var_export(array_map(function($v1,$v2){return [$v1,$v2];},$where['id'],$where['date']));

Wanna see "fancy" made "schmancy"?

(Demo)

$where = [
    'id' => [12,13,14],
    'date'=>['1999-06-12','2000-03-21','2006-09-31']
];
var_export(array_map(null, ...array_values($where)));

This this same effect as above, just with a more succinct syntax.


If anyone's trying decide which solution to use for their own project, Alex's iterated array_column() call is superior to Sahil's, IMO, because it is more flexible/robust (doesn't require hardcoding of all column names), instantly expandable if your input array has variable column, and is more succint & expressive in general.

For that matter, my final snippet (the schmancy one) is also suitable for variable input sizes and is very concise. The major difference between Alex's and mine is the generation of null valued placeholding elements.



来源:https://stackoverflow.com/questions/43948739/restructure-multidimensional-array-of-column-data-into-multidimensional-array-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!