title: PHP How can I combine two CSVs based on common fields in a rows of each csv?
body: <p>I have two CSVs:</p>
  
  <p>1st csv is something like this:</p>
  
  <pre><code>number | color | size | animal
  
  **1234** | black | big | cat
  </code></pre>
  
  <p>2nd csv is like this:</p>
  
  <pre><code>name | country | os | number | flavour | yesorno
  
  john | world | windows | **1234** | good | yes
  </code></pre>
  
  <p>What I'm trying to do is to merge both CSV's (header titles and values of each row) based on matching number values:</p>
  
  <pre><code>number | color | size | animal | name | country | os | flavour | yesorno
  
  **1234** | black | big | cat | john | world | windows | good | yes
  </code></pre>
  
  <p>I have been trying to use <code>fgetcsv</code> and used keys but I am really a newbie to php and I do not know how to that. I need to understand the logic. Could anyone please help?</p>
  
  <p>Many thanks.</p>
  
  <p>-- edit for better udnerstanding --
  based on another question on stackoverflow, I have tryed the following code, which is not working well. The two headers from both CSV files is not merged. It is also missing all the data from a csv, it only has one row of data merged.</p>
  
  <p>Code was found in another question: <a href="https://stackoverflow.com/questions/26440839/merging-two-csv-files-together-using-php">Merging two csv files together using php</a> and seemed like a perfect base for what I am trying to achieve. Unfortunately the outputed csv is malformed...</p>
  
  <pre><code>&lt;?php
  // 1st section
  $fh  = fopen('csv1.csv', 'r');
  $fhg = fopen('csv2.csv', 'r');
  
  while (($data = fgetcsv($fh, 0, ";")) !== FALSE) {
      $csv1[] = $data;
  }
  while (($data = fgetcsv($fhg, 0, ",")) !== FALSE) {
      $csv2[] = $data;
  }
  
  // 2nd section
  
  for ($x = 0; $x &lt; count($csv2data); $x++) {
      if ($x == 0) {
          unset($csv1data[0][17]);
          $line[$x] = array_merge($csv2data[0], $csv1data[17]); //header
      } else {
          $deadlook = 0;
          for ($y = 0; $y &lt;= count($csv1data); $y++) {
  
              if($csv1data[$y][17] == $csv2data[$x][0]){
              unset($csv1data[$y][17]);
              $line[$x]=array_merge($csv2data[$x],$csv1data[$y]);
              $deadlook=1;
              }
          }
          if ($deadlook == 0)
              $line[$x] = $csv2data[$x];
      }
  }
  // 3 section    
  $fp = fopen('final.csv', 'w'); //output file set here
  
  foreach ($line as $fields) {
      fputcsv($fp, $fields);
  }
  fclose($fp);
  ?&gt; 
  </code></pre>