I am really new to PHP programming, and I'm frustrated because I think this should work and it doesn't. I'm really missing something...
<?php
foreach ($datas as $name)
{
if ($name['state'] === 'MA')
{
echo
'<input type="hidden" name="id" value="' . $name['id'] . '" />' .
'<h2>' . htmlentities($name['name']) . '</h2>' .
'<p>' .
htmlentities($name['description']) . ' ' .
...
'<h1>' . $name['id'] . '</h1>';
foreach ($commentdatas as $name2)
{
if ($name['id'] == $name2['parkid'])
{
echo $name['id'] . $name2['parkid'];
}
}
}
}
?>
</div>
Everything worked well until I got to the second foreach statement. The foreach works. When I test, $name['id'] echos properly, as does $name2['parkid'].
There doesn't seem to be a problem with the system correctly identifying these, even in the loop. But inside the if statement, nothing echos at all.
Obviously something is wrong with the if statement. I've looked everywhere I can find and I'm having trouble figuring out the proper way to compare these variables. Can anyone help?
Try in_array() function
foreach ($commentdatas as $name2) {
if ($name['id'] == $name2['parkid'])
{
echo $name['id'] . $name2['parkid'];
}
}
}
replace with
if(in_array($name['id'],$commentdatas)){
echo $name['id'] . $name2['parkid'];
}
Related
I have these two associative arrays.
I want to print the matched category_id with CHECKED and the rest Un-CHECKED
Here is what I tried.
foreach ($all_available_categories as $category) {
if(in_array($category['category_id'], $current_item_categories)){
echo 'CHECKED';
}
echo '<input type="checkbox" name="item_categories_checkbox[]" value="' .$category['category_id'] . '">' . $category['category_name'] . "</br>";
}
You should do sometjhing like this:
Step1: Modify your $current_item_categories array like this:
$currentCategories = array();
foreach($current_item_categories as $currCat) {
array_push($currentCategories, $currCat['category_id']);
}
Step2: Now I am using the same logic as applied by you, with a very little modification.
foreach ($all_available_categories as $category) {
if(in_array($category['category_id'], $currentCategories)){
$checked = 'checked="checked"';
}else {
$checked = "";
}
echo '<input ' . $checked . 'type="checkbox" name="item_categories_checkbox[]" value="' .$category['category_id'] . '">' . $category['category_name'] . "</br>";
}
Note: code not tested.
Well, you could first make an associative array of current item categories, you just key it by the category id for fast lookup.
<?php
$currentCatIds = array();
foreach ($current_item_categories as $category) {
$currentCatIds[$category['category_id']] = 1;
}
foreach ($all_available_categories as $category) {
$catid = $category['category_id'];
// Forgot this one
$checked = isset($currentCatIds[$catId]) ? 'checked' : '';
echo '<input ' . $checked . ' type="checkbox" name="item_categories_checkbox[]" value="' . $catid . '" />' . $category['category_name'] . '<br />';
}
foreach ($all_available_categories as $category) {
foreach ($next_available_categories as $category1) {
if($category['category_id'] == $category1['category_id']){
echo 'CHECKED'; break;
}
}
echo '<input type="checkbox" name="item_categories_checkbox[]" value="' .$category['category_id'] . '">' . $category['category_name'] . "</br>";
}
The idea is really quite easy: loop all categories and then for each category check whether this category is checked. You are trying to do the latter using the PHP function in_array(), but that function doesn't search multi-dimensional. So that would only work if you would have an array of category id's: $ids = array('9', '13');, and then check the category id using in_array().
So if we make these modifications it works:
$ids = array();
foreach($current_item_categories as $category) {
$ids[] = $category['category_id'];
}
foreach ($all_available_categories as $category) {
if(in_array($category['category_id'], $ids)){
echo 'CHECKED';
}
echo '<input type="checkbox" name="item_categories_checkbox[]" value="' . $category['category_id'] . '">' . $category['category_name'] . '</br>';
}
An other way to do this would of course be to use two nested loops. This would no longer require an array of id's and allows for other checks to be made:
foreach ($all_available_categories as $category) {
foreach ($current_item_categories as $c) {
if ($category['category_id'] == $c['category_id']) {
echo 'CHECKED';
}
}
echo '<input type="checkbox" name="item_categories_checkbox[]" value="' . $category['category_id'] . '">' . $category['category_name'] . '</br>';
}
Finally, you should realize that your code doesn't check the checkboxes, it only prints the word "CHECKED". If that isn't what you want, you should add a checked attribute to your input element.
Credit to Frog's answer.
Here is the fully working code.
$current_ids = array();
foreach ($current_item_categories as $category) {
$current_ids[] = $category['category_id'];
}
foreach ($all_available_categories as $category) {
echo '<input type="checkbox" name="item_categories_checkbox[]" value="' . $category['category_id'] . '"';
if (in_array($category['category_id'], $current_ids)) {
echo ' CHECKED ';
}
echo ' >' . $category['category_name'] . '</br>';
}
I need the array($project_Ids) out of function any suggestion.This is in view
I can't call the function cause already is called; I just want some how to update this array().
$project_Ids=array();
function generateProperties($listP, $sizeS){
global $project_Ids;
$i=0;
foreach ($listP as $pr) {
$i++;
$pr['project_id'];
$project_Ids[$i]=$pr['project_id'];
echo "<li class='' style='cursor: pointer;height:" . $sizeSmallBlock . "px;' dds='" . $project['project_id'] . '-' . $project['project_calendar_id'] . "' id='" . $project['project_id'] . '-' . $project['project_calendar_id'] . "'>" .
$description .
"</li>";
}
}
You need to define the array inside the function, and then have the function return it!
function generateProperties($listP, $sizeS){
$project_Ids=array();
$i=0;
foreach ($listP as $pr) {
$i++;
$project_Ids[$i]=$pr['project_id'];
}
return $project_Ids;
}
// then elsewhere in your code
$project_Ids = generateProperties($listP, $sizeS);
Edit:
From looking at your foreach loop - it seems you are just getting the array values and storing them in an array? If so - just use array_values - it does exactly what you want in one line of code:
$project_Ids = array_values($listP);
It is already available outside of the function, as you have correctly defined it outside.
You may want to brush up on scope.
$project_Ids = generateProperties($listP, $sizeS);
This will work but you have to read it from end of the page after rendering all the page :)
I'm still a PHP noob, so I apologize if this is something simple.
I am creating a fairly basic search facility for a website using PHP and mySQL. I have connected to the database, selected the database, queried the table and have fetched the table columns;
$k = htmlspecialchars($_GET['k']); // Get search query
$select = mssql_query("SELECT * FROM search WHERE Title Like '%" . $k . "%'");
if( mssql_num_rows($select) < 1) {
$noResults = 'No results found for <b>' . $k . '</b>, <label for="k">Please try again.</label>';
} else {
while ($results = mssql_fetch_array($select)) {
$title = $results['Title'];
$link = $results['Link'];
$description = $results['Description'];
}
}
When I put the $results[''] columns into variables and then try to echo out each variable like so;
if( isset($noResults)) {
echo $noResults;
} else {
echo '<li>' . '<h2>' . '' . $title . '' . '</h2>' . '<p>' . $link . '</p>' . '<p>' . $description . '</p>' . '</li>';
}
it only echo's out one row matching that query however, If I was to just simple echo out the columns like so;
echo $results['Title'];
echo $results['Link'];
echo $results['Description'];
all rows matching the query will be displayed..
I'm not sure why this is happening. If someone could help me out that would be great!
You need to use a loop:
$k = mysql_real_escape_string($_GET['k']); // Get search query
$select = mssql_query("SELECT * FROM search WHERE Title Like '%" . $k . "%'");
if( mssql_num_rows($select) < 1) {
$noResults = 'No results found for <b>' . $k . '</b>, <label for="k">Please try again.</label>';
} else {
$results= array();
while ($result = mssql_fetch_array($select)) {
$results[]= $result;
}
}
if( isset($noResults)) {
echo $noResults;
} else {
echo "<ul>";
foreach($results as $result){
echo '<li>' . '<h2>' . '' . $result['title'] . '' . '</h2>' . '<p>' . $result['link'] . '</p>' . '<p>' . $result['description'] . '</p>' . '</li>';
}
echo "</ul>";
}
Do you execute the output in the while-loop?
If you execute the while-loop and call the echo after that, each resultset will overwrite the previous, and the echo will output the last resultset which was fetched.
If you call the echo in the Loop, every result set will generate "his own" output line.
If you want to hold every resultset in a variable you can use an array, which is declared in front of the loop and gets filled in the loop.
a few things are not clear from your question, but i am assuming that you are echo'ing the variables outside the loop since you are checking isset($noResults). that means you are reassigning the variables with new values in each loop of while. so ultimately you get the last one assigned to the variables. you have to either use an array to hold the values or echo it with in the loop.
i have a problem with my PHP code, i've trying to put some information i get from a database into the URL so later on i can use $_GET.
The problem is use this code:
foreach ($get_wh_list as $key => $value)
{
echo $value['id'] . "<br />";
echo "<a href='?action=hot&&id='" . $value['id'] . "'>" . $value['wh_title'] . "</a><br />";
}
Right so as you can see i'm printing the id value, when i run this page the id shows up, but when i click a link the id doesn't appear in the URL. any ideas? I really can't think of why for the life of me.
Thanks for the help.
Remove the extra "&"
foreach ($get_wh_list as $key => $value)
{
echo $value['id'] . "<br />";
echo "<a href='?action=hot&id='" . $value['id'] . "'>" . $value['wh_title'] . "</a><br />";
}
Maybe it is better to use a tested and working function for that stuff
Use http_build_query(); to Serialize an Array to Query String
Put only one '&' in url instead of two '&&'
Example :
echo "<a href='?action=hot&id='" . $value['id'] . "'>" . $value['wh_title'] . "</a><br />";
foreach ($data['tests'] as $testname => $tests) {
echo "<h1>Extraction $testname Tests</h1>\n";
$function = $testfunctions[$testname];
echo "<ul>";
foreach ($tests as $test) {
echo "<li>" . $test['description'] . ' ... ';
$extracted = $extractor->$function($test['text']);
if ($test['expected'] == $extracted) {
echo " <span style='color: green'>passed.</span></li>";
} else {
echo " <span style='color: red'>failed.</span>";
echo "<pre>Original: " . htmlspecialchars($test['text']) . "\nExpected: " . print_r($test['expected'], true) . "\nActual : " . print_r($extracted, true) . "</pre>";
}
echo "</li>";
}
echo "</ul>";}
I keep getting the error:
Warning: Invalid argument supplied for
foreach() in
C:\xampp\htdocs\test\runtests.php on
line 49
p.s. the beginning of the code is line 49, so the probelm starts with the foreach statment.
Whenever i see that, it tends to mean that the thing i'm trying to iterate through isn't an array.
Check $data['tests'] (and each inner $tests) to make sure it's not null/unset/empty, and that it's something iterable like an array. Also keep in mind that older versions of PHP (before 5.0?) don't do iterable objects very well.
One of the elements in $data["tests"] is probably not an array.
Add this before the foreach:
if (is_array($tests))
foreach ($tests as $test) {...