Restrict Search Domain - php

I have a data set that I'm searching for certain IPA symbols. I'd like to restrict the search domain in accordance with the value of $where shown in the code below, but don't know how. EDIT: Where $where is "onset" "nucleui" and "coda." Does anyone know how to restrict the search domain? (The code below is in php but the file is linked to an HTML file that a person could use to search for the IPA symbols in the data set.) EDIT: See added code at bottom.
//set up variables
$words = $table[0]; //row 1 of table
$target = $table[1]; //row 2
$indices = array(); //used to store column numbers
$IPAstr = $_POST["ipa"];
$where = $_POST["where"];
//Find $IPAstr in $target
for($i=1; $i<count($target); $i++)
{
if (mb_strpos($target[$i],$IPAstr) !== false)
$indices[] = $i;
}
//List realizations & count frequency
for($i=0; $i<count($indices); $i++)
{
$index = $indices[$i];
$ipalist = array();
echo "<table border=1><tr><td>".$target[$index]." in " . $words[$index]."</td></tr><td>";
//output each speaker and count frequency
for ($j=2; $j<count($table); $j++) {
echo ($j-1).": ".$table[$j][$index]."<br>";
$ipalist[$table[$j][$index]]++;
}
echo "<br>";
//output frequency list
foreach($ipalist as $ipa=>$fre)
echo "$ipa: $fre<br>";
echo "</td></tr></table>";
}
//Code to help search for "onset" "nuclei" and "coda"
//list onsets only
echo "Onsets only<br>";
for($col=0; $col<count($table[0]); $col++) {
$s = $table[0][$col];
if (whichSyllPart($s) == 'o') echo "$s ";
}
//list nuclei only
echo "Nuclei only<br>";
for($col=0; $col<count($table[0]); $col++) {
$s = $table[0][$col];
if (whichSyllPart($s) == 'n') echo "$s ";
}
//list codas only
echo "Codas only<br>";
for($col=0; $col<count($table[0]); $col++) {
$s = $table[0][$col];
if (whichSyllPart($s) == 'c') echo "$s ";
}

In order to restrict the search domain you need to enter the following code as part of the "//Find $IPAstr in $target" section of the code.
//Find $IPAstr in $target
for($i=1; $i<count($target); $i++)
{
if ($where == whichSyllPart($words[$i])){
if (mb_strpos($target[$i],$IPAstr) !== false)
$indices[] = $i;
}
else if ($where == "everywhere"){
if (mb_strpos($target[$i],$IPAstr) !== false)
$indices[] = $i;
}
}
For this to run you need a function whichSyllPart()
function whichSyllPart($sy)
{
$pt = $sy[strlen($sy)-1];
return($pt);
}
This adds an if/else if statement including the whichSyllPart() function that restricts the search according to the value of $where.

Related

How to export data in excel dynamically using PHPSpreadsheet/PHPExcel in PHP?

I have some data which I am trying to export in an excel sheet with help of PHP, data is dynamic so I am facing difficulties while exporting them. I have tried both in PHPExcel (which is deprecated) and in PHPSpreadsheet too. I have tried lots of solutions given in the community but no help!
How to print data dynamically in excel using PHP?
Data needs to print from column number = 36 (AK) and Row = 2
Data that needs to export:
MongoDB\Model\BSONDocument Object
(
[storage:ArrayObject:private] => Array
(
[dd1] => PWC>Yes,Deloitte>Yes,Media Type>Category A,Coverage Type>Quote,Service Line>TAX,Score>5
[dd2] => Service Line>Personal tax
)
)
though [dd1] contains labels and values too, like PWC[this is lable] >Yes [this is value], that's why I explode label and value separately.
Also, I have printed the labels in the first row already that's why I explode the value of the below code and also made a check if ($temp[0] == $labels[$i]) then only print value.
Completed Code:
$cols = 36;
for ($i = 0; $i < count($labels); $i++) {
if ($result["qualification"]["dd1"] != "") {
$found = false;
for ($j = 0; $j < count($dd1); $j++) {
$temp = explode(">", $dd1[$j]);
//need to check the weather labels of the header and these labels are the same? then only print
if ($temp[0] == $labels[$i]) {
$name = explode(">", $dd1[$j]);
$sheet->setCellValueByColumnAndRow($cols+1, $j+1, $name[1]);
$found = true;
break;
}
}
if (!$found)
$sheet->setCellValueByColumnAndRow($cols+1, $j+1 , "");
} else
$sheet->setCellValueByColumnAndRow($cols+1 , $j+1 , "");
if ($result["qualification"]["dd2"] != "") {
$found = false;
for ($j = 0; $j < count($dd2); $j++) {
$temp = explode(">", $dd2[$j]);
if ($temp[0] == $labels[$i]) {
$name = explode(">", $dd2[$j]);
$sheet->setCellValueByColumnAndRow( $cols, $j + 2, $name[1] );
$found = true;
break;
}
}
if (!$found)
$sheet->setCellValueByColumnAndRow($cols, $j+1 , "");
} else {
$sheet->setCellValueByColumnAndRow($cols , $j+1 , "");
}
$cols = $cols + 2;
}
I have tried lots of methods but no help but I made something in the HTML table which is working fine, unfortunately, I do not need an HTML table to excel because it has a lot of format issues and cons.
for reference only-
Here is the same working snippet in HTML Table:
$inn_table = "";
if($result['qualification']['dd1']!="") {
$dd1 = explode(",",$result['qualification']['dd1']);
}
if($result['qualification']['dd2']!=""){
$dd2 = explode(",",$result['qualification']['dd2']);
}
for($i=0;$i<count($labels);$i++) {
if($result['qualification']['dd1']!="") {
$found=false;
for($j=0;$j<count($dd1);$j++) {
$temp = explode(">",$dd1[$j]);
if($temp[0]==$labels[$i]) {
$name = explode(">",$dd1[$j]);
$inn_table .= '<td>'.$name[1].'</td>';
$found=true;
break;
}
}
if(!$found)
$inn_table .= "<td> </td>";
}
else
$inn_table .= "<td> </td>";
if($result['qualification']['dd2']!="") {
$found=false;
// echo '<pre>ass';print_r($dd2);
for($j=0;$j<count($dd2);$j++) {
$temp = explode(">",$dd2[$j]);
if($temp[0]==$labels[$i]) {
$name = explode(">",$dd2[$j]);
$inn_table .= '<td>'.$name[1].'</td>';
$found=true;
break;
}
}
if(!$found)
$inn_table .= '<td> </td>';
}
else{
//if(count($dd2Array)>0){
$inn_table .= '<td> </td>';
//}
}
} //end of for($i=0;$i<count($labels);$i++)
echo $inn_table;
echo "</tr>";

Display values without array (print_r)

I have a function that displays the actors photos from TMDB to my website is there a way that I can make it print without an array, it prints only with print_r I want to know if I can print it like echo or print.
This is the code:
public function getCasts($movieID)
{
if (empty($movieID)) return;
function cmpcast($a, $b)
{
return ($a["order"]>$b["order"]);
}
$temp = $this->_call("movie/" . $movieID . "/casts");
$casts = $temp['cast'];
$temp = array();
if (count($casts) > 0)
{
usort($casts, "cmpcast");
foreach ($casts as &$actor) {
if (!empty($actor['profile_path'])) {
for ($i=6; $i<count($temp['id']); $i++)
if ($temp['name'][$i] == $actor['name']) $temp['char'][$i] .= " / ".str_replace('(voice)', '(hang)', $actor['character']);
if (!in_array($actor['name'], (array) $temp['name'])) {
$temp['pic'][] = "<div style='margin-top:15px;' align='center'><div style='width:140px;margin-right:8px;display:inline-block;vertical-align:top;'><img style='width:130px;height:130px;border-radius:50%;' src='".$this->getImageURL().$actor['profile_path']."'><br />".$actor['name']."<br />".$actor['character']."</div></div>";
}
}
}
}
return $temp;
}
You could use some kind of loop. Use a for loop if you want to limit the number of item you echo.
For example :
$casts = getCasts(1);
for ($i = 0; $i < 5; $i++) {
if (isset($casts['pic'][$i])) {
echo $casts['pic'][$i];
}
}
Hope it helps.

Simple Search Engine Only Works With One SQL Row

I'm making a rather simple search engine with PHP and I've ran into a problem... The engine will only work for one SQL row. In the table the PHP is connected to, there are two rows. One named "The Painful Truth" and the other "Darkness Rising". If you type "darkness" or "rising" into the search bar it will come back with "Darkness Rising" as expected. However, if you input "the", "painful", or "truth" into the bar it will come back with zero results.(P.S. "The Painful Truth" is the first entry in the table) I attempted to debug it by listing out the song names in the table, the search, and the array after exploding the song names. They all line up like they should work, but alas, they don't.
The code below takes the input and removes characters and spaces
$lower = strtolower($_POST["text"]);
$characterRemover = preg_replace('/[^ \w]+/', '', $lower);
$search = str_replace(' ' , '' , $characterRemover);
echo "<strong>". $search . "</strong><br>";
The code below takes data from the database, explodes the string and tries to find a match.
while($row = $result->fetch_assoc()) {
$Slower = strtolower($row["song_name"]);
echo "Song Name: " . $Slower . "<br>";
$song_name = explode(" " , $Slower);
// list array
$arrlength = count($song_name);
for($x = 0; $x < $arrlength; $x++) {
echo $song_name[$x];
echo "<br>";
}
if (in_array($search, $song_name) !== false) {
$song_result = $row["song_name"];
} else {
$song_result = "0 results buddy";
}
}
here's how it looks when I search for "the":
What's happening here is that the loop is running for every single row and the variable $song_result is being overwritten. Try to use a flag $found to get the song.
$found = false;
while(!$found && ($row = $result->fetch_assoc())) {
$Slower = strtolower($row["song_name"]);
echo "Song Name: " . $Slower . "<br>";
$song_name = explode(" " , $Slower);
// list array
$arrlength = count($song_name);
for($x = 0; $x < $arrlength; $x++) {
echo $song_name[$x];
echo "<br>";
}
if (in_array($search, $song_name) !== false) {
$song_result = $row["song_name"];
$found = true;
} else {
$song_result = "0 results buddy";
}
}
If you want to capture every song, then use an array or concatenate a string:
$songs = [];
while($row = $result->fetch_assoc()) {
$Slower = strtolower($row["song_name"]);
echo "Song Name: " . $Slower . "<br>";
$song_name = explode(" " , $Slower);
// list array
$arrlength = count($song_name);
for($x = 0; $x < $arrlength; $x++) {
echo $song_name[$x];
echo "<br>";
}
if (in_array($search, $song_name) !== false) {
$songs[] = $row["song_name"];
}
}
if (count($songs)) {
$song_result = implode('<br>', $songs);
} else {
$song_result = "0 results buddy";
}
Note: You should follow JimL's suggestion and request the info filtering the DB query via the WHERE clause. And then just show the result of the query. ;)
<?php
//Kindly make sure you have create a connection and select a db. this is a sample code to search from mysql db using data supplied
$msg=$_POST['search'];
if(isset($msg)){
$search=explode(' ',$msg);
$len=count($search);
$query="select * from news where ";
for($m=0;$m<$len;$m++){
$query.=" post like '%{$search[$m]}%' || ";
}
$query.=" post like '%{$msg}%' order by upload_date desc";
if($get=mysqli_query($connect,$query)){
$contentSearch=array();
$i=0;
while($row=mysqli_fetch_assoc($get)){
contentSearch[$i]=$row;
$i++;
}
echo"List of Search Items<br>";
print_r($contentSearch);
}
}

PHP: Undefined offset in stripos

Hello! Im working with AJAX with DB and when trying to render my db in an option and select tag it gives me an "Undefined offset error".
Here is my code:
$sql = "SELECT word FROM words";
$result = mysql_query($sql);
$response = "";
$size = 0;
if($result === FALSE) {
die(mysql_error());
}
while ($row = mysql_fetch_array($result)) {
for($i = 0; $i < count($row); $i ++) {
$pos = stripos(strtolower($row[$i]), $pattern); //Here marks the error
if(!($pos === false)) {
$size ++;
$word = $row[$i];
$response .= "<option value=\"$word\">$word</option>";
}
}
}
if($size > 0) {
echo "<select id=\"list\" size=$size onclick=\"selectValue()\">$response</select>";
}
The idea of this app is you can start typing any word and it will search for words that matches with the input, displaying it first in an option HTML tag and when no more options are matched it's displayed in a select HTML tag.
It's kind of working but it displays this errors. Can someone help me? Thanks!!
Here is modified script:
while ($row = mysql_fetch_assoc($result)) {
$pos = stripos(strtolower($row['word']), $pattern);
if(!($pos === false)) {
$size ++;
$word = $row['word'];
$response .= "<option value=\"$word\">$word</option>";
}
}
But actually next script will run faster:
if ($result = mysql_query("SELECT word FROM words where word like '%".mysql_real_escape_string($pattern)."%'")) {
$response = "";
$size = 0;
while ($row = mysql_fetch_assoc($result)) {
$size ++;
$word = htmlspecialchars($row['word']);
$response .= "<option value=\"$word\">$word</option>";
}
echo "<select id=\"list\" size=$size onclick=\"selectValue()\">$response</select>";
}
And yes - use mysqli instead of mysql, mysql_ functions are deprecated.

Weird behaviour when searching for char in array string elements

<?php
ini_set('error_reporting', '-1');
ini_set('display_errors', '1');
ini_set('apc.enabled', '0');
gc_enable();
$array = array("php", "php_php", "php_php", "php_php", "php");
$arraysize = count($array);
$style = " style='border: 1px solid black;'";
$strcmpcharcount = 0;
$equalcmpcharcount = 0;
foreach ($array as $key)
{
$strcmpcharcount = 0;
$equalcmpcharcount = 0;
if (strstr($key, "_") !== false)
{
$strstr[] = "found";
$explodedstring1[] = explode("_", $key);
}
else
{
$strstr[] = "not found";
$explodedstring1[] = "not found";
}
if (strpos($key, "_") !== false)
{
$strpos[] = "found";
$explodedstring2[] = explode("_", $key);
}
else
{
$strpos[] = "not found";
$explodedstring2[] = "not found";
}
if (preg_match("/[^_+$]/", $key))
{
$preg_match[] = "found";
$explodedstring3[] = explode("_", $key);
}
else
{
$preg_match[] = "not found";
$explodedstring3[] = "not found";
}
$keysize = strlen($key);
for ($i = 0; $i < $keysize; $i++)
{
if (strcmp($key[$i], "_") === 0) { $strcmpcharcount++; }
}
for ($j = 0; $j < $keysize; $j++)
{
if ($key[$j] === "_") { $equalcmpcharcount++; }
}
if ($strcmpcharcount > 0)
{
$strcmp[] = "found";
$explodedstring4[] = explode("_", $key);
}
else
{
$strcmp[] = "not found";
$explodedstring4[] = "not found";
}
if ($equalcmpcharcount > 0)
{
$equalcmp[] = "found";
$explodedstring5[] = explode("_", $key);
}
else
{
$equalcmp[] = "not found";
$explodedstring5[] = "not found";
}
}
echo "<table$style>
<th$style>
<tr>
<td$style>strstr()</td>
<td$style>strpos()</td>
<td$style>preg_match()</td>
<td$style>strcmp()</td>
<td$style>'==='</td>
</tr>
</th>";
for($k = 0; $k < $arraysize; $k++)
{
echo "<tr>
<td$style>$strstr[$k]</td>
<td$style>$strpos[$k]</td>
<td$style>$preg_match[$k]</td>
<td$style>$strcmp[$k]</td>
<td$style>$equalcmp[$k]</td>
</tr>";
}
echo "</table>";
exit();
?>
The problem is with first two functions - they randomly fails to find the underscore char. In fact I called more than 50 times the script to got proper results. Added and preg_match() test but just to know I'm not sure if it has valid regex.
You're adding new elements to $strstr, $strpos tables and so on and in the end you do for... and printing from these tables where $k keys don't necessarily have to exists.
Check var_dump or print_r on these tables and you will see that in fact they got elements, but their indexes aren't matched with $array indexes (and i guess that's what you want to achieve).
You can change foreach ($array as $key) to foreach ($array as $index => $key) and all occurences like $strstr[] = "found"; to $strstr[$index] = "found"; (also for other recognision methods) and then run the script again to see results.
In last block (for($k = 0; $k < $arraysize; $k++)...) you should either validate if $strstr[$k] (and other arrays) exists before printing it, or print these arrays separately by foreach.
You can also make one table for results and make it multidimensional with function names as keys in the first level and put results in there.

Categories