使用php合并多个数组

使用php合并多个数组,php,arrays,excel,parsing,xlsx,Php,Arrays,Excel,Parsing,Xlsx,我目前正试图找出如何在php中合并数组集合 foreach ($Col as $Row) { echo("<pre>"); print_r($Row); // This returns the arrays below echo("</pre>"); } 无论如何,我可以将以下数组合并到一个数组中,因为我只想从所有数组中获取用户名并将它们合并到一个新数组中。试试这个 $values = array( array('First Nam

我目前正试图找出如何在php中合并数组集合

foreach ($Col as $Row)
{   
    echo("<pre>");
      print_r($Row); // This returns the arrays below
    echo("</pre>");
}  
无论如何,我可以将以下数组合并到一个数组中,因为我只想从所有数组中获取用户名并将它们合并到一个新数组中。

试试这个

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

  • 弹出第一个数组(看起来像标题),搜索可用作标记的
    username

  • 在确定了它的位置之后,您可以在一个简单的循环中使用它。考虑这个例子:

    #1

    $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>';
    
    #2

    Array
    (
        [0] => DBob
        [1] => Asimp
        [2] => LJames
    )
    

    为什么您的问题与Excel有关?似乎您的数据已经被捕获到单个变量$Col中。您的代码工作得很好,但您已经在变量values中硬编码了数组。如何将结果添加到foreach循环的数组中?@coletrain
    $value
    应该是硬编码的,因为这只是一个样本数据。给定,如果示例数据(在本例中为
    $values
    )的结构与
    $Col
    相同,则其工作原理应相同。您只需要替换,例如:
    $values=$Col
    
    $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>';
    
    Array
    (
        [0] => DBob
        [1] => Asimp
        [2] => LJames
    )