How to use php count to insert a couple of words (string) in MySQL
array sample
$a=array("a","b","c","d");
$b=array("b","c","d","f");
and i am using for loop to produce this result
ab ac ad af bb bc bd bf cb cc cd cf db dc dd df
one array $ element aligns element of array $ b
and i want to count the element of this solution the problem is i want bd and db to be the same, we admit it appears twice how can i do this in php? after that i will write all solution insert count in MySQL
source to share
quick response. Sort the two items before combining them, then check if they exist in the answer set.
$a=array("a","b","c","d");
$b=array("b","c","d","f");
$res = array();
foreach($a as $v1) {
foreach($b as $v2) {
$t = array($v1, $v2);
asort($t);
$val = implode('', $t);
if(!in_array($val, $res))
$res[] = $val;
}
}
print_r($res);
source to share
A better algorithm would be to create only valid strings from the end of the for loop.
Let me explain earlier.
$ a = array ("a", "b", "c", "d");
$ B = array ("b", "c", "d", "f");
$ x = array_diff ($ a, $ b); // X will only contain "a" elements.
$ y = array_uintersect () // Syntax check. will give you matches "b" "c" "d"
In the forloop used, use $ x instead of $ a.
This will produce the following output: "ab ac ad af"
And $ y has matches. So you can use it to create "bb", "cc", "dd"
If you only want to count one, then the answer you want is the counter (match) + the result of your for loop.
source to share
Try the following:
$a = array("a", "b", "c", "d");
$b = array("b", "c", "d", "f");
sort($a);
sort($b);
$result = [];
for ($i = 0; $i < count($a); $i++) {
for ($j = 0; $j < (count($b)); $j++) {
if ($b[$j] < $a[$i]) {
continue;
}
$result[] = $a[$i] . $b[$j];
}
}
$result = array_unique($result, SORT_STRING);
var_dump($result);
source to share
My decision:
<?php
$a=array("a","b","c","d");
$b=array("b","c","d","f");
$c=array();
$d=array();
$ii=0;
foreach($a as $dat){
if(!isset($c[$dat])){
$c[$dat]=$ii;
$ii++;
}
}
foreach($b as $dat){
if(!isset($c[$dat])){
$c[$dat]=$ii;
$ii++;
}
}
$count=0;
for ($i = 0; $i < count($a); $i++) {
for ($j = 0; $j < (count($b)); $j++) {
if(!isset($d[$c[$a[$i]]][$c[$b[$j]]])){
echo $a[$i].$b[$j]."<br/>";
$d[$c[$a[$i]]][$c[$b[$j]]]=1;
$d[$c[$b[$j]]][$c[$a[$i]]]=1;
$count++;
}
}
}
echo "The count is: ".$count;
?>
source to share