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条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)