简体   繁体   English

如何将多个php数组转换为一个多维数组?

[英]How to transform multiple php arrays into one multi-dimensional array?

I'm trying to transform many arrays with mostly similar data into a single array that has arrays in the keys for when there are more than one value.我试图将具有大部分相似数据的许多数组转换为一个数组,该数组在键中有多个值时具有数组。 I think this is done as a pivot table in sql, but I would like to do this in PHP for other reasons.我认为这是作为 sql 中的数据透视表完成的,但由于其他原因我想在 PHP 中执行此操作。

I would like to transform:我想转型:

$og=array();
$og[] = array('a'=>'cat', 'b'=>'beer', 'c'=>'wood');
$og[] = array('a'=>'cat', 'b'=>'beer', 'c'=>'bamboo');
$og[] = array('a'=>'cat', 'b'=>'beer', 'c'=>'concrete');

Into:进入:

$new_array(
  'a'=>'cat',
  'b'=>'beer',
  'c'=>array('wood','bamboo','concrete')
);

I feel like this should be simple but for some reason I can't figure it out!我觉得这应该很简单,但由于某种原因我无法弄清楚!

You could use the following to accomplish this:您可以使用以下方法来完成此操作:

$new_array = array();

foreach( $og as $data ) {
    foreach( $data as $k => $v ) {

        if( ! isset( $new_array[$k] ) )
            $new_array[$k] = array();

        $new_array[$k][] = $v;

    }
}

foreach( $new_array as $k => $data ) {
    $new_array[$k] = array_unique($data);

    if( count($new_array[$k]) == 1 )
        $new_array[$k] = $new_array[$k][0];

}

Check out array_unique() and array_merge() .查看array_unique()array_merge() There may be a faster way to accomplish this, but this works.可能有更快的方法来实现这一点,但这是有效的。

You can iterate over the $og array and create your new array, like so:您可以遍历 $og 数组并创建新数组,如下所示:

$new_array = array();
foreach($og as $parr=>$carr) {
    foreach($carr as $key=>$value) {
        if(!array_key_exists($key,$new_array)) {
            $new_array[$key] = $value;
        }else if(!in_array($value,$new_array)) {
            if(is_array($new_array[$key])) {
                array_push($new_array[$key],$value);
            } else {
                $currentVal = $new_array[$key];
                $new_array[$key] = array($key=>$currentVal);
                array_push($new_array[$key],$value);
            }
        }
    }
}

Here is a PHP Fiddle demo .这是一个 PHP Fiddle 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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