dongmeiran609914 2014-05-29 06:12
浏览 51
已采纳

使用php合并多个数组

I am currently trying to figure out how to merge a collection of arrays in php.

foreach ($Col as $Row)
{   
    echo("<pre>");
      print_r($Row); // This returns the arrays below
    echo("</pre>");
}  

When I run the foreach statement it returns the following:

Array
(
  [0] => First Name
  [1] => Last Name
  [2] => Username
)

Array
(
  [0] => Bob
  [1] => Dill
  [2] => DBob
)


Array
(
  [0] => Amy
  [1] => Simpson
  [2] => Asimp
)

Array
(
  [0] => Doug
  [1] => James
  [2] => LJames
)

Is there anyway I can merge the following arrays into one array as I am interested in only grabbing the username from all of the arrays and merging them into a new array.

  • 写回答

2条回答 默认 最新

  • duanqin4238 2014-05-29 06:38
    关注

    Since you want to get the usernames, could just :

    1. point it directly (which is index 2)

    2. pop the first array (which looks like a header), search for username which can be used as your marker.

    After determining where it its, you can use it in a simple loop. Consider this example:

    #1

    $values = array( array('First Name', 'Last Name', 'Username'), array('Bob', 'Dill', 'DBob'), array('Amy', 'Simpson', 'Asimp'), array('Doug', 'James', 'LJames'), );
    $usernames = array();
    array_shift($values);
    foreach($values as $key => $value) {
        $usernames[] = $value[2];
    }
    

    #2

    $values = array( array('First Name', 'Last Name', 'Username'), array('Bob', 'Dill', 'DBob'), array('Amy', 'Simpson', 'Asimp'), array('Doug', 'James', 'LJames'), );
    $usernames = array();
    $header = array_shift($values);
    $username_key = array_search('Username', $header); // find out which column is username
    foreach($values as $key => $value) {
        $usernames[] = $value[$username_key];
    }
    
    echo '<pre>';
    print_r($usernames);
    echo '</pre>';
    

    Sample Output:

    Array
    (
        [0] => DBob
        [1] => Asimp
        [2] => LJames
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况