【问题标题】:php concat array values into new array phpphp concat 数组值到新数组 php
【发布时间】:2018-07-19 04:52:24
【问题描述】:

我有一个数组,其中的数组表示数据库中的值。

db 表中有超过 100 列,因此实际计数远高于下面这个示例的 6 个值,子数组(数组中的数组)索引 0-5。

列在子数组的每个索引中,行在主数组的每个索引中。

这是我的主数组和子数组:

Array
(
    [0] => Array
        (
            [0] => N
            [1] => N
            [2] => Y
            [3] => Y
            [4] => Y
            [5] => Y
)
 [1] => Array
        (
            [0] => N
            [1] => N
            [2] => Y
            [3] => Y
            [4] => N
            [5] => Y
)
[2] => Array
        (
            [0] => N
            [1] => N
            [2] => Y
            [3] => Y
            [4] => N
            [5] => Y
)
[3] => Array
        (
            [0] => Y
            [1] => Y
            [2] => Y
            [3] => Y
            [4] => Y
            [5] => Y
)

我需要做的是将每个子索引的所有值连接到一个数组中,如下所示:

Array
( 
            [0] => N,N,N,Y
            [1] => N,N,N,Y
            [2] => Y,Y,Y,Y
            [3] => Y,Y,Y,Y
            [4] => Y,N,N,Y
            [5] => Y,Y,Y,Y
)

总会有相同数量的列(子索引),但会有不同数量的行(索引)。

【问题讨论】:

    标签: php arrays multidimensional-array


    【解决方案1】:

    这个想法是按列获取数据,你很幸运,有一个内置函数。它的array_column

    首先,获取列数,然后简单地使用 for 循环。然后只需使用implode 并将其分配到一个新容器中:

    $new = array(); // container
    $count = count($arr[0]); // get the number of colums
    for ($i = 0; $i < $count; $i++) {
        // get the data by column number ($i), then implode and push inside
        $new[] = implode(',', array_column($arr, $i));
    }
    

    这是一个示例output

    【讨论】:

    • 你真是个摇滚老兄!非常感谢。这非常有效!
    • @Yourguide 很高兴这对您有所帮助
    【解决方案2】:

    我假设您已将 $column 定义为 db 表中的总列数。使用array_column根据列键获取值。

    $result = array();
    for ($i = 0; $i < $column; $i++) {
        $res = array_column($arr, $i);
        $result[] = implode(",", $res);
    }
    

    有关array_column功能的更多信息,请查看此link

    哦,只是想让您知道array_column 函数仅适用于 PHP 5.5 及更高版本。

    【讨论】:

      【解决方案3】:

      检查这是不是你想要的

      $arr = array(//your array); 
      $newArr = array(); //data wil lbe saved here
      foreach($arr as $arr_one){
          $string = "";
          foreach($arr_one as $subArr){
              $string.=$subArr.",";
          }
          array_push($newArr,rtrim($string,','));
      }
      
      var_dump($newArr);
      

      【讨论】:

        【解决方案4】:

        避免使用像 forwhile 这样的显式循环。使用array_map(可以遍历数组的可变数量):

        $result = array_map(function (...$column) {
            return implode(',', $column);
        }, ...$array);
        

        这里是the demo

        顺便说一句,在linear algebra 中,这被称为矩阵的transpose

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-05-12
          • 2014-10-30
          • 2018-12-27
          • 1970-01-01
          • 1970-01-01
          • 2016-08-01
          • 2013-02-12
          相关资源
          最近更新 更多