i am currently having problem with searching through json file, and i am searching and showing faculties based on searched word but it only shows the value when i type in the full name, how can i get search to work if i like only type first few characters and show the results with name starting with it.
here is my code:
<?php
if(isset($_GET['search_word']))
{
$search_word=$_GET['search_word'];
$string = file_get_contents("faculty_info.json");
$jfo = json_decode($string);
// copy the posts array to a php var
$posts = $jfo->faculty_info;
// listing posts
foreach ($posts as $post) {
if($post->name == "$search_word"){
echo $post->name;
echo "<br>";
echo $post->division;
echo "<br>";
echo $post->school;
echo "<br>";
echo $post->designation;
echo "<br>";
echo $post->email;
echo "<br>";
echo $post->room;
echo "<br>";
echo "<br>";
}
}
}
?>
Try this
$post->name = 'How are you?';
$search_word = "How";
$pos = strpos($post->name, $search_word);
if ( $pos !== false && $pos == 0) {
echo 'found';
//do your script
}
You may also want to replace strpos with stripos in case you need to handle case insensitive searches.
Related
I am newer to PHP and I am able to get the desired output but I am doing it one index position at a time. I am returning data from a .txt file and I need to insert this data into an HTML table I am creating using PHP. BUT FIRST I need to be able to get the same output without typing out every index position. I tried to use a forloop but it kept outputting only one line.
I manually outputted the lines from the file and it works. What loop in PHP would be best to achieve the same results and output these elements? IMPORTANT, as is I am able to sort and rsort (I want to be able to do this so if it can be implemented in the loop that would be awesome) any help is more than I have right now.
PHP
$books = array();
if ($fp)
{
while(true)
{
$lines_in_file = count(file($filename));
$line = fgets($fp);
if (feof($fp))
{
break;
}
$line_ctr++;
list($title, $author, $pubdate, $isbn) = explode('*', $line);
$new_line = explode('*', $line);
for($ii= 1; $ii <= $lines_in_file; $ii++){
$lines = fgets($fp); //Read each line
$member = trim($lines);
array_push($books, $member);
}
//This foreach only brings back the first like in the txt file, why?
$cntr = 0;
foreach($books as $element){
$cntr++;
$table .= "<tr>";
$table .= "<td>".$title."</td>";
$table .= "<td>".$author."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$isbn."</td>";
$table .= "</tr>\n"; //added newline
echo $element;
}
//sort($books);
// rsort($books);
echo $books[0];
echo "<br>";
echo $books[1];
echo "<br>";
echo $books[2];
echo "<br>";
echo $books[3];
echo "<br>";
echo $books[4];
echo "<br>";
echo $books[5];
echo "<br>";
echo $books[6];
echo "<br>";
echo $books[7];
echo "<br>";
echo $books[8];
echo "<br>";
echo $books[9];
echo "<br>";
echo $books[10];
echo "<br>";
echo $books[11];
echo "<br>";
echo $books[12];
echo "<br>";
echo $books[13];
echo "<br>";
echo $books[14];
echo "<br>";
echo $books[15];
echo "<br>";
echo $books[16];
echo "<br>";
echo $books[17];
}//END WHILE LOOP
fclose($fp ); //Close file
}
Having to make a few guesses here but i believe the file is going to look like:
title*author*pubdate*isbn
title*author*pubdate*isbn
title*author*pubdate*isb
if this is wrong, let me know
as long as the fie is not to large read it in to an array:
$book_array=file('book_file.txt');
//print_r($book_array); //is it an array of the books, one book per array key
now to separate each line:
foreach($book_array as $line){
$line_sep=explode('*',$line);
// with no sorting option you could just echo inside the loop
//if you want to keep sorting options we have to keep the separated lines
$new_book_array[]=$line_sep;
}
unset($book_array);//free up memory if needed
//print_r($new_book_array);//is it a multi-d array, book then the 4 elements
to sort our new multidimensoanl array:
usort($new_book_array, function($a, $b) {
return strcmp($a['0'], $b['0']);;
}); //this sorts on key 0 in your case title:
//print_r($new_book_array); // has it sorted properly
for display:
loop again
echo '<table><tr><th>Title</th><th>Author</th><th>Pub Date</th><th>ISBN</th></tr>';
foreach($new_book_array as $book){
//print_r($book); //is it each indervidual book array with 4 elements
echo '<tr><td>'.$book[0].'</td><td>'.$book[1].'</td><td>'.$book[2].'</td><td>'.$book[3].'</td></tr>';
}
echo '</table>';
i need to sort some strings and match them with links, this is what i do:
$name_link = $dom->find('div[class=link] strong');
Returns array [0]-[5] containing strings such as NowDownload.eu
$code_link = $dom->find('div[class=link] code');
Returns links that match the names from 0-5, as in link [0] belongs to name [0]
I do not know the order in which they are returned, NowDownload.Eu, could be $code_link[4] or $code_link [3], but the name array will match it in order.
Now, i need $code_link[4] // lets say its NowDownload.Eu to become $link1 every time
so i do this
$i = 0;
while (!empty($code_link[$i]))
SortLinks($name_link, $code_link, $i); // pass all links and names to function, and counter
$i++;
}
function SortLinks($name_link, $code_link, &$i) { // counter is passed by reference since it has to increase after the function
$string = $name_link[$i]->plaintext; // name_link is saved as string
$string = serialize($string); // They are returned in a odd format, not searcheble unless i serialize
if (strpos($string, 'NowDownload.eu')) { // if string contains NowDownload.eu
$link1 = $code_link[$i]->plaintext;
$link1 = html_entity_decode($link1);
return $link1; // return link1
}
elseif (strpos($string, 'Fileswap')) {
$link2 = $code_link[$i]->plaintext;
$link2 = html_entity_decode($link2);
return $link2;
}
elseif (strpos($string, 'Mirrorcreator')) {
$link3 = $code_link[$i]->plaintext;
$link3 = html_entity_decode($link3);
return $link3;
}
elseif (strpos($string, 'Uploaded')) {
$link4 = $code_link[$i]->plaintext;
$link4 = html_entity_decode($link4);
return $link4;
}
elseif (strpos($string, 'Ziddu')) {
$link5 = $code_link[$i]->plaintext;
$link5 = html_entity_decode($link5);
return $link5;
}
elseif (strpos($string, 'ZippyShare')) {
$link6 = $code_link[$i]->plaintext;
$link6 = html_entity_decode($link6);
return $link6;
}
}
echo $link1 . '<br>';
echo $link2 . '<br>';
echo $link3 . '<br>';
echo $link4 . '<br>';
echo $link5 . '<br>';
echo $link6 . '<br>';
die();
I know they it finds the link, i have tested it before, but i wanted to make it a function, and it messed up, is my logic faulty or is there an issue with the way i pass the variables/ararys ?
I don't know why you pass $i as reference since you use it just for reading it. You could return an array contaning the named links and using it like so :
$all_links = SortLinks($name_link,$code_link);
echo $all_links['link1'].'<br/>';
echo $all_links['link2'].'<br/>';
You will have to put your loop inside the function, not outside.
I have an array coming from a .csv file. These are coming from a real estate program. In the second column I have the words For Sale and in the third column the words For Rent that are indicated only on the rows that are concerned. Otherwise the cell is empty. I want to display a list rows only For Sale for example. Of course then if the user clicks on a link in one of the rows, the appropriate page will be displayed.
I can't seem to target the text in the column, and I can't permit that the words For Sale be used throughout the entire array because they could appear in another column (description for example).
I have tried this, but to no avail.
/* The array is $arrCSV */
foreach($arrCSV as $book) {
if($book[1] === For Sale) {
echo '<div>';
}
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
I also tried this:
foreach($arrCSV as $key => $book) {
if($book['1'] == 'For Sale') {
echo '<div>';
}
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
Do you mean:
foreach($arrCSV as $key => $book) {
if($book['1'] == 'For Sale') {
echo '<div></div>';
}else{
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
}
I found a solution here:
PHP: Taking Array (CSV) And Intelligently Returning Information
$searchCity = 'For Sale'; //or whatever you are looking for
$file = file_get_contents('annonces.csv');
$results = array();
$lines = explode("\n",$file);
//use any line delim as the 1st param,
//im deciding on \n but idk how your file is encoded
foreach($lines as $line){
//split the line
$col = explode(";",$line);
//and you know city is the 3rd element
if(trim($col[1]) == $searchCity){
$results[] = $col;
}
}
And then:
foreach($results as $Rockband)
{
echo "<tr>";
foreach($Rockband as $item)
{
echo "<td>$item</td>";
}
echo "</tr>";
}
As you can see I'm learning. It turns out that by formulating a question, a series of similar posts are displayed, which is much quicker and easier than using google. Thanks.
I have an rss feed that I am reading into. I need to retrieve certain data from the field in this feed.
This is the example feed data :
<content:encoded><![CDATA[
<b>When:</b><br />
Weekly Event - Every Thursday: 1:30 PM to 3:30 PM (CT)<br /><br />
<b>Where:</b><br />
100 West Street<BR>2nd floor<BR>Gainesville<BR>
<br>.....
How do I pull out the data for When: and Where: respectively? I attempted to use regex but I am unsure if I am not accessing the data correctly or if my regex expression is wrong. I'm not set on using regex.
This is my code:
foreach ($x->channel->item as $event) {
$eventCounter++;
$rowColor = ($eventCounter % 2 == 0) ? '#FFFFFF' : '#F1F1F1';
$content = $event->children('http://purl.org/rss/1.0/modules/content/');
$contents = $content->encoded;
echo '<tr style="background-color:' . $rowColor . '">';
echo '<td>';
//echo "<a id=buttonRed href='$event->link' title='$event->title' target='_blank'>" . $event->title . "</a>";
echo "" . $event->title . "";
echo '</td>';
echo '<td>';
$re = '%when\:\s*</b>\s*(.|\s)<br \/><br \/>$/i';
if (preg_match($re, $contents, $matches)) {
$date = $matches;
}
echo $date;
echo '</td>';
echo '<td>';
$re = '/^When\:<\/b>()$/';
if (preg_match($re, $contents, $matches)) {
$location = $matches;
}
echo $location;
echo '</td>';
echo '<td>';
echo "<a id=buttonRed href='$event->link' title='$event->title' target='_blank'>Click Here To Register</a>";
echo '</td>';
echo '</tr>';
}
The two $res are just my attempt to get the data out using different regex expressions. Let me know where I am going wrong. Thanks
The following should sort of get you there. (I wrote this from the top of my head and it does not exactly following your XML syntax. But you get the idea.)
<?php
$str = "<root><b>When:</b> whenwhen <b>Where:</b> wherewhere</root>";
$doc = new DOMDocument();
$doc->loadXML($str);
$when = $where = "";
$target = null;
foreach ($doc->documentElement->childNodes as $node) {
if ($node->tagName == "b") {
if (++$i == 1) {
$target = &$when;
} else {
$target = &$where;
}
}
if ($target !== null && $node->nodeType === XML_TEXT_NODE) {
$target .= $node->nodeValue;
}
}
var_dump($when, $where);
I had a problem like this and I ended up using YQL. Take a good look at the page-scraping code given there, especially the select command. Then go the the console and put in your own select statement, specifying the feed url and the xpath to the nodes you're wanting. Select JSON format. Then go down to the bottom of the page, get the REST query url, and use it in a jquery jsonp request. MAGIC!
please, don't extract data from XML-documents via regex.
The long answer is e.g. here: https://stackoverflow.com/a/335446/313145
The short answer is: it is not easier to use regex and will break often.
For a multiple choice quiz application i would like to show the dummy answers with the correct answer. But with the correct answer being in a different position at each different question.
This is what i've tried but it doesn't seem to be working:
if ($question->type == 1)
{
echo "<div id='dummy_answers'>";
//Show Dummy
echo '<h3>Dummy Answers</h3>';
//Get Dummy Answers
$query = $this->test_model->getDummyAnswers($question->id);
$dummy_num = 1;
foreach ($query->result() as $row)
{
$rand_number = rand(1, 3);
if ($dummy_num == $rand_number)
{
$dummy_num = $rand_number + 2;
echo '<h4>Answer '.$dummy_num.'</h4>';
echo '<p>';
echo $row->option;
echo '</p>';
//Now echo the real answer
echo '<h4>Answer '.$rand_number.'</h4>';
echo '<p>';
echo $row->option;
echo '</p>'; //Get id's for each.echo $row->id;
}
else
{
echo '<h4>Answer '.$dummy_num.'</h4>';
echo '<p>';
echo $row->option;
echo '</p>';
$dummy_num++;
}
}
echo '</div>';
echo ' <hr/>';
}
?>
You should use shuffle function.
In your case it will be:
if ($question->type == 1)
{
echo "<div id='dummy_answers'>";
//Show Dummy
echo '<h3>Dummy Answers</h3>';
//Get Dummy Answers
$query = $this->test_model->getDummyAnswers($question->id);
$answers=$query->result();
shuffle($answers);
foreach ($answers as $nr=>$row)
{
echo '<h4>Answer '.($nr+1).'</h4>';
echo '<p>';
echo $row->option;
echo '</p>';
}
echo '</div>';
echo ' <hr/>';
}
?>
Put the answers in an array the use shuffle
$random_array = shuffle($answers);
All you need to do is put the keys for your answers in an array and call shuffle(). Something like this:
$keys = array_keys($answers);
shuffle($keys);
for ($key in $keys) {
echo $answers[$key];
}
I would suggest putting all the answers into an array and using the shuffle() function to randomize them. Once they're shuffled, just iterate the array with a loop and build the markup.
You could put the results into an array (1 correct and 3 incorrect), then shuffle, then output them?
$answers = array();
array_push($answers, "answer1");
array_push($answers, "answer2");
array_push($answers, "answer3");
array_push($answers, "answer4");
shuffle($answers);
foreach ($answers as $answer) {
echo $answer;
}