简体   繁体   中英

How to merge two arrays into one array?

I have two arrays that looks like this:

  0 => string '2014-02-14' (length=10)
  1 => string '2014-03-14' (length=10)
  2 => string '2014-04-14' (length=10)
  3 => string '2014-05-14' (length=10)
  4 => string '2014-06-16' (length=10)
  5 => string '2014-07-14' (length=10)

and the other:

  0 => string '2014-01-30' (length=10)
  1 => string '2014-02-27' (length=10)
  2 => string '2014-03-31' (length=10)
  3 => string '2014-04-30' (length=10)
  4 => string '2014-05-29' (length=10)
  5 => string '2014-06-30' (length=10)

what i want to do is to merge this two arrays in a specific way so i can use it forward to CSV, so i need to be like this:

  0 => string '2014-02-14,2014-02-14'

so it should be firstarray_value , secondarray_value for the new array, is there anyway to manipulate this two arrays to be come one array in that for described above?

Just try with:

$array1 = array( /* your data */ );
$array2 = array( /* your data */ );
$output = array();

for ($i = 0; $i < count($array1); ++$i) {
  $output[] = $array1[$i] . ',' . $array2[$i];
}

To use it with fputcsv :

for ($i = 0; $i < count($array1); ++$i) {
  $output[] = array($array1[$i], $array2[$i]);
}

foreach ($output as $fields) {
    fputcsv($fp, $fields);
}

Edit:

You can merge those arrays quicker with:

$output = array_map(null, $array1, $array2);

and then also:

foreach ($output as $fields) {
    fputcsv($fp, $fields);
}
$array3 = array();
foreach($array1 as $key=>$val){
    $array3[] = $val.",".$array2[$key];
}
print_r($array3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM