代码之家  ›  专栏  ›  技术社区  ›  Ty W

将多个一维阵列转换为二维阵列列的最有效方法

  •  1
  • Ty W  · 技术社区  · 15 年前

    当我在写 for 今天早些时候,我想一定有一个更整洁的方法来做这个…所以我想我应该问问。我简短地寻找了一个重复的问题,但没有看到任何明显的问题。

    问题:

    给定n个长度为m的数组,将其转换为m行x n列的2d数组

    例子:

    $id   = [1,5,2,8,6]
    $name = [a,b,c,d,e]
    $result = [[1,a],
               [5,b],
               [2,c],
               [8,d],
               [6,e]]
    

    我的解决方案:

    很直截了当,可能不是最优的,但它确实有效:

    <?php
    // $row is returned from a DB query
    // $row['<var>'] is a comma separated string of values
    $categories = array();
    $ids = explode(",", $row['ids']);
    $names = explode(",", $row['names']);
    $titles = explode(",", $row['titles']);
    for($i = 0; $i < count($ids); $i++) {
        $categories[] = array("id" => $ids[$i],
                              "name" => $names[$i],
                              "title" => $titles[$i]);
    }
    ?>
    

    注意:我没有把name=>value位放在规范中,但是如果有办法保持它的话,那就太棒了。

    2 回复  |  直到 15 年前
        1
  •  3
  •   anomareh    15 年前

    也许这个?不确定是否更有效,但肯定更干净。

    /*
    Using the below data:
    
    $row['ids'] = '1,2,3';
    $row['names'] = 'a,b,c';
    $row['titles'] = 'title1,title2,title3';
    */
    
    $categories = array_map(NULL,
      explode(',', $row['ids']),
      explode(',', $row['names']),
      explode(',', $row['titles'])
    );
    
    // If you must retain keys then use instead:
    $withKeys = array();
    
    foreach ($row as $k => $v) {
        $v = explode(',', $v);
    
        foreach ($v as $k2 => $v2) {
            $withKeys[$k2][$k] = $v[$k2];
        }
    }
    
    print_r($categories);
    print_r($withKeys);
    
    /*
    $categories:
    
    array
      0 => 
        array
          0 => int 1
          1 => string 'a' (length=1)
          2 => string 'title1' (length=6)
    ...
    
    $withKeys:
    
    array
      0 =>
        array
          'ids' => int 1
          'names' => string 'a' (length=1)
          'titles' => string 'title1' (length=6)
    ...
    */
    

    在这个页面上对4个结果做了一个简单的快速基准测试,得到了以下结果:

    // Using the following data set:
    $row = array(
        'ids'       =>  '1,2,3,4,5',
        'names'     =>  'abc,def,ghi,jkl,mno',
        'titles'    =>  'pqrs,tuvw,xyzA,BCDE,FGHI'
    );
    
    /*
    For 10,000 iterations,
    
    Merge, for:
    0.52803611755371
    
    Merge, func:
    0.94854116439819
    
    Merge, array_map:
    0.30260396003723
    
    Merge, foreach:
    0.40261697769165
    */
    
        2
  •  1
  •   Peter Bailey    15 年前

    是的, array_combine()

    $result = array_combine( $id, $name );
    

    编辑

    下面是我如何处理您的数据转换

    function convertRow( $row )
    {
      $length = null;
      $keys = array();
    
      foreach ( $row as $key => $value )
      {
        $row[$key] = explode( ',', $value );
        if ( !is_null( $length ) && $length != count( $row[$key] ) )
        {
          throw new Exception( 'Lengths don not match' );
        }
        $length = count( $row[$key] );
    
        // Cheap way to produce a singular - might break on some words
        $keys[$key] = preg_replace( "/s$/", '', $key );
      }
    
      $output = array();
    
      for ( $i = 0; $i < $length; $i++ )
      {
        foreach ( $keys as $key => $singular )
        {
          $output[$i][$singular] = $row[$key][$i];
        }
      }
    
      return $output;
    }
    

    和一个测试

    $row = convertRow( $row );
    echo '<pre>';
    print_r( $row );