I have an ajax live search script working except that it only seems to be returning the first row of the array. Don't know if it is something with my loop, however, if anyone can spot error, would greatly appreciate help as I cannot seem to find it. I am not including javascript cause I'm pretty sure that is not error as php file is firing. It is just echoing the first hit and not iterating through others.
//run query on dbase then use mysql_fetch_array to place in array form
while($a = mysql_fetch_array($res,MYSQL_BOTH))
{
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
$n = $a['first']." ".$a['last'];
if ($hint=="")
{
$hint=''.$n.'';
}
else
{
$hint=$hint.'<br>'.$n.'';// we do not seem to get here
}
}
}
}
// Set output to "no suggestion" if no hints were found
// or to the correct values
}//close while fetch
echo $hint;
You're overwriting your $hint variable on every while loop iteration. Try declaring it before the while (remove where you have it now)
$hint = "";
while($a = mysql_fetch_array($res,MYSQL_BOTH))
{
Try to use this method:
<?
$output = '';
while($a = mysql_fetch_array($res,MYSQL_BOTH)) {
if (strlen($q) > 0) {
for($i=0; $i<count($a); $i++) {
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q)))) {
$n = $a['first']." ".$a['last'];
if ($output == "") {
$output = ''.$n.'';
} else {
$output .= '<br>'.$n.'';
}
}
}
}
}
echo $output;
?>
Related
I been trying to parse statements/questions from a forum site using a DOM parser.
Its working fine, it extracts all statements in the forum. So, i tried to put a limit of extracting statements using a if condition. it still doesn't fix the problem.
I thought the problem in structuring the if condition, so i ran the loop separately and it worked..
the code goes as follows:
<?php
$i = 1;
$elementCount=0;
while(true){
require_once('dom/simple_html_dom.php');
$html = file_get_html('http://www.usmleforum.com/forum/index.php?forum=1&Page='.$i);
foreach ($html->find("tr") as $row) {
$element = $row->find('td.FootNotes2',0);
if ($element == null) { continue; }
$textNode = array_filter($element->nodes, function ($n) {
return $n->nodetype == 3; //Text node type, like in jQuery
});
if (!empty($textNode)) {
$text = current($textNode);
echo $text."<br>";
$elementCount++;
}
}
if($elementCount==12){
break;
}
$i++;
}
?>
So, even after adding the if condition for 12 statements it still runs for forever.
now the if condition alone:
<?php
$i = 1;
$elementCount=0;
while(true){
echo "harish".$i."<br>";
$elementCount++;
if($elementCount==12){
break;
}
$i++;
}
?>
It works fine, prints only 12 given statement.
Any help is appreciated...
I'm not sure you are incrementing the $elementCount correctly but since I cannot see the output of your code I'm not sure.
I would move the break statement before the $elementCount++ and also echo the $elementCount to figure out what's really going on.
The resulting code would be like this:
<?php
$i = 1;
$elementCount=0;
while(true){
require_once('dom/simple_html_dom.php');
$html = file_get_html('http://www.usmleforum.com/forum/index.php?forum=1&Page='.$i);
foreach ($html->find("tr") as $row) {
$element = $row->find('td.FootNotes2',0);
if ($element == null) { continue; }
$textNode = array_filter($element->nodes, function ($n) {
return $n->nodetype == 3; //Text node type, like in jQuery
});
if (!empty($textNode)) {
$text = current($textNode);
echo $text."<br>";
echo $elementCount;
if($elementCount===12){
break;
}
$elementCount++;
}
}
$i++;
}
?>
You should better structure your code. So you would see that you increment the elementCount inside the foreach.
As you are checking outside of the foreach for the exact elementCount it can happen, that your counter rises above 12 elements and now will run forever.
You could just change the loop to
while($elementCount < 12) {...}
So you are checking if you have less than 12 and not exactly 12 or to:
if ($elementCount >= 12) {...}
I can't figure out how to test if there's a next item in my array by using the key to test against. I think this is better explained in code. I know there's an easier way, I'm just a noob!
Basically I want to know if there is another item in the array and if so get the ->comp_id value.
for($i=0; $i<count($allcomps); $i++)
{
if($allcomps[$i]->comp_id == $curCompID)
{
$currentIndex = $i;
if($allcomps[$i+1]->comp_id == null )
{
echo "there isn't a next";
}
//echo $allcomps[$currentIndex+1]->comp_id;
}
}
You're already looping through allcomps, so why do you need a check for the next one?
Why not check within the loop?
for($i=0; $i<count($allcomps); $i++) {
if (isset($allcomps[$i]->comp_id) and $allcomps[$i]->comp_id == $curCompID) {
$currentIndex = $i;
}
}
I think a foreach might be even easier:
foreach($allcomps as $i=>$comp) {
if (isset($comp->comp_id) and $comp->comp_id == $curCompID) {
$currentIndex = $i;
}
}
I have managed to decode some JSON in PHP successfully (not as painful as I thought), but it's been such a long time since I've done any real PHP, my brain has drawn a blank on the following.
The decoded json looks like this
[Array]
item {
[0]
{
[live]=>
[name]=>Paul
[value]=>10
}
[1]
{
[live]=>1
[name]=>Fred
[value]=>32
}
and so on
The problem I'm having is this - I'm trying to iterate through the structure to test first if live==1 and then if it's the first live name, to output it as a selected value to a HTML drop down.
I'm currently trying like this
$t = 0;
$count = 0;
foreach($decode['items'] as $option=>$value)
{
print_r("option = $option\n");
if ($option=>isLive == 1)
{
print_r("isLive is true for $option[$count]['names']\n");
if ($t == 0)
{
echo "<option value=$option[name] selected>$value[name]</option>";
$t = 1;
}
else
echo "<option value=$option[name]>$value[name]</option>";
}
else
{
print_r("isLive is false for $option[$count]=>name\n");
}
$count++;
}
the problem is that I don't seem to be able to get the if statement correct for this to work. This is probably a seriously simple problem and will no doubt make me face palm, but I could do with a pointer in the right direction here!
If the json is like you showed us you could not iterate over anything with your foreach because your array does not contain a key named items.
Using the provided structure this should do the trick:
foreach($decode["item"] as $item) {
if($item->live == 1) {
...
} else {
...
}
}
If $item is not an object use $item['live'] instead.
P.S.: You should really turn error_reporting on. $option=>isLive is no valid syntax.
$t = 0;
$count = 0;
$arr = json_decode($json,true);
foreach($arr as $key=>$val)
{
print_r($key);
if($val['live'])
{
if($t == 0)
{
echo '<option value='.$val['name'].' selected>'.$val['name'].'</option>';
$t = 1;
}
else
{
echo '<option value='.$val['name'].'>'.$val['name'].'</option>';
}
}
else
{
echo $key.' not printed cause it hasn\'t live set to true';
}
$count++;
}
Am trying to build a JSON array from a php array
This is my function in my controller
function latest_pheeds() {
if($this->isLogged() == true) {
$this->load->model('pheed_model');
$data = $this->pheed_model->get_latest_pheeds();
$last = end($data);
echo "[";
for($i = 0; $i < count($data); $i++) {
echo '{"user_id":"'.$data[$i][0]['user_id'].'",';
echo '"pheed_id":"'.$data[$i][0]['pheed_id'].'",';
echo '"pheed":"'.$data[$i][0]['pheed'].'",';
echo '"datetime":"'.$data[$i][0]['datetime'].'",';
if($i == count($data)) {
echo '"comments":"'.$data[$i][0]['comments'].'"}';
}else {
echo '"comments":"'.$data[$i][0]['comments'].'"},';
}
}
echo "]";
}
return false;
}
It returns a json array like this
[{"user_id":"9","pheed_id":"2","pheed":"This is my first real pheed, its got potential ","datetime":"1313188898","comments":"0"},{"user_id":"9","pheed_id":"11","pheed":"My stomach being hurting all day","datetime":"1313422390","comments":"0"},{"user_id":"9","pheed_id":"11","pheed":"My stomach being hurting all day","datetime":"1313422390","comments":"0"},{"user_id":"9","pheed_id":"10","pheed":"Thank God for stackoverflow.com ","datetime":"1313358605","comments":"0"},]
But i cant seem to access it with jquery
I believe the problem rests with the trailing comma at the end of your array.
Rather than try to encode it yourself, use PHP's json_encode function. It's been tested and verified many, many times, so you don't have to reinvent the wheel.
Already voted up #derekerdmann, but thought I would add...
Your code will work, if you change:
if($i == count($data)) {
to
if($i == count($data) - 1) {
But, don't do that. If you are just putting everything from each member of the $data array into the json, then you should be able to just json_encode($data). If you are only pulling out certain parts, then build up a secondary array of your filtered data and json_encode that instead.
function latest_pheeds() {
if($this->isLogged() == true) {
$this->load->model('pheed_model');
$data = $this->pheed_model->get_latest_pheeds();
$filtered_items = array();
foreach ($data as $member) {
$filtered_item = array();
$filtered_item['user_id'] = $member['user_id'];
$filtered_item['pheed_id'] = $member['pheed_id'];
...
...
$filtered_items[] = $filtered_item;
}
echo json_encode($filtered_items);
}
return false;
}
I have programmed a script with the goto command but on the server where I want to execute the script there is a previous PHP version (<5.3), so I have to change the code. The structure of the code goes like that:
for($i = 0; $i < 30; $i++) // print 30 articles
{
$x = 0;
// choose a a feed from the db
// parse it
a:
foreach($feed->get_items($x, 1) as $item)
{
// create a unique id for the article of the feed
if($id == $dbid)
{
// if this id exists in the db, take the next article of the same feed which is not in the db
$x++;
goto a;
}
else
{
// print the original article you grabbed
}
} // end of foreach
} // end of for
I have tested everything. Do you have any ideas how can I retransform this code without goto in order to be executed properly???
This questions demonstrates why goto should be avoided. It lets you get away without thinking about the algorithm enough.
The standard way to do this is with a flag. I hope you were not expecting a "herezthecode kthxbai" sort of an answer, but in this case the best way to explain it would be to write the code -
for($i=0;$i<30;$++){
$x=0;
do {
$found = false;
foreach($feed->get_items($x,1) as $item){
// get $id
if($id==$dbid){
$found = true;
break;
}else{
// other things
}
}
$x++;
} while($found);
}
Without knowing how the ->get_items() call behaves you could use this brute-force method in lieu of the goto-switch:
for($i = 0; $i < 30; $i++)
{
$x = 0;
$a = 1;
while ($a--)
foreach($feed->get_items($x, 1) as $item)
{
if($id == $dbid)
{
$x++;
$a=1; break;
}
else
{
}
} // end of foreach
} // end of for
The label gets replaced by a while and a self-fulfulling stop condition. And the goto becomes a break and resets the $a stop condition.
Something like this would probably work...
function loop(){
foreach($feed->get_items($x,1) as $item){
if($id==$dbid){
$x++;
loop();
}else{
}
}
}
for($i=0;$i<30;$++){
$x=0;
loop();
}
I'm sorry, I removed all the comments, they were annoying.
Move the declaration of $x outside of the for loop and replace your label/goto combination with a break, like so...
$x=0;
for($i=0;$i<30;$++) //print 30 articles
{
foreach($feed->get_items($x,1) as $item)
{
// create a unique id for the article of the feed
if($id==$dbid)
{
//if this id exists in the db,take the next article of the same feed which is not in the db
$x++;
continue;
}
else
{
//print the original article you grabbed
}
} // end of foreach
}//end of for
Agree with unset - using break will break if loop and keep iterating through for loop