How to use php to get unique word pair (row) and insert into mysql table

code:

$a=array("apple","bird","cat","dog");
$b=array("bird","cat","dog","flog");

$res = array();
foreach($a as $v1) {
  foreach($b as $v2) {
    $t = array($v1, $v2);
    asort($t);
    $val = implode('', $t);
    if(!in_array($val, $res))
      print $val;
      print "/";
  }
}

      

the code is rewritten with @pala_ form this article How to use php, count a word (string) pair array in MySQL

and here's the output

applebird/applecat/appledog/appleflog/birdbird/birdcat/birddog/birdflog/birdcat/catcat/catdog/catflog/birddog/catdog/dogdog/dogflog/

      

ok and my question is if I want to split this combination string into two lines

eg: applebird ----> apple bird and insert into MySQL table

as:

source | target

apple | bird

apple | cat

apple | dog

........ something like this, any idea? thank.

0


source to share


2 answers


Remove implode, store them as multidimensional array .:



$a=array("apple","bird","cat","dog");
$b=array("bird","cat","dog","flog");

$res = array();
foreach($a as $v1) {
  foreach($b as $v2) {
    $t = array($v1, $v2);
    asort($t);    
    if(!in_array($t, $res)) {
      print $res[] = $t;
      // alternatively, instead of building them into an array for further processing
      // you could immediately execute your sql query here, using $t[0], $t[1] as
      // the values (thanks to comments).  If you are using prepared statements
      // (which you should be), if you prepare the statement outside of the loops
      // you can simply execute it here, passing $t[0] and $t[1] as the bound parameters
    }
  }
}

foreach($res as $pair) {
  ...
  // build your query using whatever mysql interface you are using
  // $pair[0] will be one word, $pair[1] will be the other
}

      

+2


source


I have slightly modified the code you may need:

<?php
$a=array("apple","bird","cat","dog");
$b=array("bird","cat","dog","flog");

$res=array();
$finalString="";
foreach($a as $v1) {
  foreach($b as $v2) {
    $t=array($v1,$v2);
    asort($t);
    $val=implode('|',$t);
    if(!in_array($val, $res))
      $finalString.=$val."/";
  }
}
echo $finalString;
?>

      

Output:



apple | bird / apple | cat / apple | dog / apple | smack / bird | birds / bird | cat / bird | dogs / birds | smack / bird | cat / cat | cat / cat | dog / cat | flogged / bird | dog / cat | dog / dog | dog / dog | smack /

further you can explode this based on "/"

This might help you.

0


source







All Articles