0

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
  • Why your problem is concerned with Excel ? Commented May 29, 2014 at 9:21
  • Its seems that your data are already grabbed into the single variable $Col. Commented May 29, 2014 at 9:22

2 Answers 2

1

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
)
Sign up to request clarification or add additional context in comments.

2 Comments

Your code works great except you've hard coded the array inside of the values variable. How can I add my results inside of an array from the foreach loop?
@coletrain the $values are supposed to be hardcoded because that is just a sample data. given, if the sample data (which is in this example, is $values) are the same in structure as your $Col then it should work the same. you just need to substitute, like :$values = $Col;
0

Try this one

$arr = array();
foreach ($Col as $Row)
{   
    foreach($Row as $k=>$val){
      $arr[count($arr)]=$val;
     }

}  

print_r($arr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.