fork download
  1. <?php
  2.  
  3. $columnNames = 'QuestionContent | OptionType | NoofAnswers | Answer | ReplyType | QuestionMarks';
  4. $columnNames = explode( ' | ', $columnNames );
  5.  
  6. $rows = <<<END
  7. Name these 2 flowers | A-F | 2 | C | Multiple | 5
  8.   What is 2+2? | A-D | 1 | ABD | Single | 5
  9. END;
  10. $rows = explode( "\n", $rows );
  11. foreach ( $rows as &$row ) {
  12. $row = array_map( trim, explode( ' | ', $row ) );
  13. $row = array_combine( $columnNames, $row );
  14. }
  15.  
  16. echo "Before:\n";
  17. var_export( $rows );
  18.  
  19. // Do this (preferably) before looping over the rows:
  20. $specialOptionTypes = array(
  21. 'Yes or No' => array( 'Y', 'N' ),
  22. 'True or False' => array( 'T', 'F' ),
  23. );
  24.  
  25. foreach ( $rows as &$row ) {
  26. // Do this for each row:
  27. if ( array_key_exists( $row['OptionType'], $specialOptionTypes ) ) {
  28. $options = $specialOptionTypes[ $row['OptionType'] ];
  29. } else if ( preg_match( '/^([A-Z])-([A-Z])$/', $row['OptionType'], $match ) ) {
  30. $options = range( $match[1], $match[2] );
  31. } else {
  32. // issue warning about unrecognized option type
  33. $options = array();
  34. }
  35. $right = str_split( $row['Answer'] ); // or explode() on a delimiter, if any
  36. $wrong = array_diff( $options, $right );
  37. $row['WrongAnswers'] = implode( '', $wrong ); // if you actually want a string
  38. }
  39.  
  40. echo "\nAfter:\n";
  41. var_export( $rows );
  42.  
Success #stdin #stdout 0.02s 13112KB
stdin
Standard input is empty
stdout
Before:
array (
  0 => 
  array (
    'QuestionContent' => 'Name these 2 flowers',
    'OptionType' => 'A-F',
    'NoofAnswers' => '2',
    'Answer' => 'C',
    'ReplyType' => 'Multiple',
    'QuestionMarks' => '5',
  ),
  1 => 
  array (
    'QuestionContent' => 'What is 2+2?',
    'OptionType' => 'A-D',
    'NoofAnswers' => '1',
    'Answer' => 'ABD',
    'ReplyType' => 'Single',
    'QuestionMarks' => '5',
  ),
)
After:
array (
  0 => 
  array (
    'QuestionContent' => 'Name these 2 flowers',
    'OptionType' => 'A-F',
    'NoofAnswers' => '2',
    'Answer' => 'C',
    'ReplyType' => 'Multiple',
    'QuestionMarks' => '5',
    'WrongAnswers' => 'ABDEF',
  ),
  1 => 
  array (
    'QuestionContent' => 'What is 2+2?',
    'OptionType' => 'A-D',
    'NoofAnswers' => '1',
    'Answer' => 'ABD',
    'ReplyType' => 'Single',
    'QuestionMarks' => '5',
    'WrongAnswers' => 'C',
  ),
)