if(count($search)==0) {
for($i=0;$i<count($about);$i++) {
$bd->insert("search","page_title,page_description,page_url,image_id","'About','{$about[$i]['image_title']}','http://religiousbrands.in/demo/about.php?search=".$about[$i]['id']."','{$about[$i]['uniq_id']}'");
}
} else {
for($i=0;$i<count($about);$i++) {
for($k=0,$j=0;$k<=$i,$j<count($search);$j++,$k++) {
if($search[$j]['image_id']==$about[$i]['uniq_id']) {
echo "update".$i.'and'.$k.'and'.$j;
echo"<br>";
$bd->update("search",
"page_title='About',page_description='{$about[$i]['image_title']}',page_url='http://religiousbrands.in/demo/about.php?search=".$about[$i]['id']."' ","image_id='{$about[$i]['uniq_id']}' limit 1");
}
}
}
}
$search is an array which I am getting from my database . first I m checking if the search table is empty or not . if empty then insert the values in the search table .
$about is also an array which i am getting from my database . if $search is not empty Then I am updating the value but checking first that $search[$j]['image_id']===$about[$i][uniq_id] and HERE IS MY PROBLEM START :
Suppose in my table about there are 3 entries ie :
uniq_id=1
uniq_id=2
uniq_id=3
and In my table search there are 2 entries ie:
image_id=1
image_id=2
So the search table is not empty So it will follow the 2nd condition. So i was trying that table $about[1]['uniq_id'] should check for $search[1]['image_id'] and $search[2]['image_id'] and etc $search[$i]['image_id'] if the table has any values
but I my for loop is not working like I want So anybody can help me in this
You'll need to know which rows in the "search" table need adding (INSERT) and which ones need updating.
Perhaps try looping through the "search" array first and find which "image_id" values you have.
$image_ids = array();
foreach ($search as $item) {
$image_ids[] = $item['image_id'];
}
Next, loop through the "about" array. Use the ID's in the "$image_ids" array to determine whether you need to UPDATE or INSERT an item.
foreach ($about as $item) {
if (in_array($item['image_id'], $image_ids)) {
// Item already exists. Update it.
} else {
// Item doesn't exist. Add it.
}
}
This is also much faster than putting loops inside loops.
Related
I have a question regarding php and sql. In the database I have a shop table 'x' in which there is a tags column containing mixed tags from which to filter the collection for the product using the operator 'like'. I have to compare the filtered collection with the collections in column 1 of the store '. If these two collections are equal, then from the store's table in column 2 I can retrieve the appropriate value and enter it into the csv file.
In php I have downloaded the column with tags from the 'x' store, but I have no idea how to add to the category that I searched for by query and compare it with the data from the store 's' column. I tried to explode the resulting strings from the foreach loop with explode () to get an array from each cell in the column, but got the primitive array that was fetched from the database. I also tried a regular for loop but it also failed.
How can you get this one value from the tags column and compare it with the data from another column ?
public static function findEmpikCategory()
{
$empik_lilante_categories = MysqlProvider::getEmpikCategory(); // empik and lilante categories from empik_categories in which the 'collection' is included
// get a specific category (lilante_category) from empik_categories
foreach($empik_lilante_categories as $categories)
{
$lilante_category_from_empik[] = $categories['lilante_category'];
}
return $lilante_category_from_empik;
}
//$lilante_category = explode(",", $lilante_category_for_offers_products, 0);
// searching lilante categories from the shopifyProductsLilante array
public static function findLilanteCategory()
{
$empik_cateries_equals_lilante_categories = MysqlProvider::getEmpikCategoryEqualLilanteCategory(); // empik categories corresponding to lilante categories
$lilante_category_to_check = CSVFileGenerator::findEmpikCategory();
$lilante_category_for_offers_products = MysqlProvider::getLilanteCategoryByOffersEmpik(); // lilante categories for all empik products
//print_r($lilante_category_to_check);
foreach($lilante_category_for_offers_products as $lilanteCategories)
{
foreach($lilanteCategories as $lilanteCategory)
{
echo "<br/>";
//print_r($lilanteCategory);
echo "<br/>";
print_r(explode(",", $lilanteCategory, 0));
//echo "<br/>";
// echo gettype($lilanteCategory) . "<br>"; // each element is a string
// print_r($lilanteCategory);
}
}
foreach($lilante_category_to_check as $lilanteCategoryFromEmpik)
{
echo "<br/>";
print_r($lilanteCategoryFromEmpik);
echo "<br/>";
}
//fclose($file_open);
return ;
}
I have a for-each statement based off a php generated query..
I am trying to figure out how I can make sure all the IDDestinations of the records are the same.
For example in my current query I have 2 records with an IDDestination of 12, one record with an IDDestination of 9 and the last is 3.
I know how to do this in the query but I am trying to generate a message to the user if the IDDestinations are not equivalent.
My code so far.
foreach($results as $row) {
$IDDestination =(int) $row['IDDestination'];
if ($IDDestination == $IDDestination){
echo "<script>alert('All Courses Match Destination.');</script>";
} else {
echo "<script>alert('Courses have different Destinations);</script>";
}
var_dump($IDDestination);
}
This is currently just verifying that each record has an IDDestination Present and tells ME All courses Match.
How can I make it so the INTEGERS are equivalent and give me the same message?
Here's one way; use a variable outside your loop to determine if it's ok or not:
$everything_matches = true;
$id = null;
foreach($results as $row) {
// Set it for the first record.
if($id === null)
$id = $row['IDDestination'];
// If the current iteration's ID matches the first record, $everything_matches
// will stay true, otherwise it's false and we should kill the loop.
if($id != $row['IDDestination']) {
$everything_matches = false;
break;
}
}
// Output your message
$message = $everything_matches ? 'All courses match destination.' : 'Courses have different destinations.';
echo '<script>alert("' . $message . '");</script>';
I am trying to combine the results from 2 queries into a single array but am having problems getting the correct code.
I have a table called PrimaryEvents that I query to add to an array. This query works ok:
$rows = query("SELECT * FROM PrimaryEvents WHERE unit = ? ORDER BY event", $unit);
I add the data to an array using the following:
foreach ($rows as $row)
{
// $event = lookup($row["event"]); (removed as spotted by sergio not required)
$event["event"] = $row["event"];
$event["validity"] = $row["validity"];
$event["eventsrequired"] = $row["eventsrequired"];
$event["unit"] = $row["unit"];
$event["role"] = $row["role"];
//now we have the data lets try and do something to it
if ($event["role"] == "0")
{
//then the user is active so change value to a YES
$event["role"] = "ALL";
}
//add our stock to the portfolio array
$portfolio[] = $event;
}
So far everything works well. I would like to query a separate table and add certain results to the array portfolio[];
$rowsCompleted = query("SELECT * FROM portfolio WHERE id = ? ORDER BY name", $_SESSION["id"]);
My original plan was to use the following additional code to add the data of interest to the portfolio[] but it doesn't work:
//now add individual stats to the array
foreach($rowsCompleted as $row)
{
if ($portfolio["event"] == $row["name"]
{
//then add our number and date to the array
$portfolio["datecompleted"] = $row["datecompleted"];
$portfolio["number"] = $row["number"];
}
//else do nothing
}
My final aim was to pull the datacompleted value and number value from the portfolio table and then add it to the array ONLY if the event name matches the name in portfolio array.
Hopefully I have described my problem and required behaviour well enough.
Thanks for nay help that can be offered, I am new to php/sql so learning as I go.
Andy
EDIT:
Also tried the following loop to try and loop through the array:
//now add individual stats to the array
foreach($rowsCompleted as $row)
{
foreach ($portfolio["event"] as $item)
{
if ($portfolio["event"] == $row["name"]
{
//then add our number and date to the array
$portfolio["datecompleted"] = $row["datecompleted"];
$portfolio["number"] = $row["number"];
}
}
//else do nothing
}
EDIT2: To try and make my question more clear: The Primary-events table lists all the events a specific user has to complete. The portfolio table tracks which events have been completed by the user (by means of date-completed and number).
I want to run a query that lists all the events from Primary-events, then into those results add the date-completed and number from the users portfolio. If the answer is blank from the portfolio then the user has not yet completed the event but I would still like to list it from the Primary-events table data.
I tried 2 queries to start with as it seemed to follow what I was trying to achieve.
EDIT3:
New code with help from Barmar
foreach ($rows as $row) {
$event = lookup($row["event"]);
$event["event"] = $row["event"];
$event["validity"] = $row["validity"];
// $event["datecompleted"] = $row["datecompleted"];
// $event["number"] = $row["number"];
$event["eventsrequired"] = $row["eventsrequired"];
$event["unit"] = $row["unit"];
$event["role"] = $row["role"];
//now we have the data lets try and do something to it
if ($event["role"] == "0") {
//then the user is active so change value to a YES
$event["role"] = "ALL";
}
//add our stock to the portfolio array
$portfolio[] = $event;
//now add individual stats to the array
foreach ($rowsCompleted as $row) {
foreach ($portfolio as &$item) {
if ($item["event"] == $row["name"]) {
//then add our number and date to the array
$item["datecompleted"] = $row["datecompleted"];
$item["number"] = $row["number"];
}
}
}
}
The page still isn't being displayed by chrome so guessing i've missed something.
EDIT4: Page displayed, I am now getting undefined index errors when the table is rendered on the html page.
Specifically the undefined index errors are for date-completed and number. I am taking it to mean that these values are not being added to the portfolio array? Do try and help I have added an Else statement (as below) to ensure that even if the event isn't available the index is:
//now add individual stats to the array
foreach($rowsCompleted as $row)
{
foreach ($portfolio as &$item)
{
if ($item["event"] == $row["name"])
{
//then add our number and date to the array
$item["datecompleted"] = $row["datecompleted"];
$item["number"] = $row["number"];
}
else
{
$item["datecompleted"] = "Never";
$item["number"] = "0";
}
}
}
EDIT 5: Near Success. Sorry to reopen this but I have just noticed behaviour I wasn't expecting: The nested loop only sets the date-completed and number for the first value to matches from the portfolio table. The follow on values are not set. It would seem like the nested loop isn't stepping through all of the portfolio values, and just exiting once the first "event" == "name".
EDIT 6: Sample data and clarification on desired functions:
portfolio sample data
|id|name |number|datacompleted
|21|event1 |3 |2014-07-07
|15|event1 |5 |2014-07-05
|21|event2 |5 |2014-05-08
|15|event1 |1 |2013-05-05
id is the id of the user that completed the event
number is the number of events completed
PrimaryEvents sample data
|id|event |validity|eventsrequired
|1 |event1 |7 |10
|1 |event2 |25 |1
|1 |event3 |12 |50
id is the id of the user that created the entry (used for historic purpose only)
The desired functionality is:
The query should create a an array to allow a html table to be created of everything within the Primary-events table. This table lists the events the user must complete.
The second query or current nested loop should gather the data from the portfolio table for the current user id, then match the event name to the name in the Primary-events array and update (if present) the number and date-completed value. (I.E populate the data for the events that the user has completed).
The current code merges the data from portfolio only for the first match, but then the nested loop seems to exit.
Hopefully this is a more clear description of what I am trying to achieve.
EDIT: I have changed the functionality to use the Left join statement below but am still having problems:
The table only contains some of the events from primary-events table and not all of them. The events being pulled over are only those that the user has completed, the ones the user has not yet completed are not being shown.
EDIT: This query seems to work:
$allEvents = query("SELECT * FROM PrimaryEvents LEFT JOIN portfolio ON (PrimaryEvents.event = portfolio.name) WHERE PrimaryEvents.event = ? AND (portfolio.id = ? Or portfolio.id is null) ORDER BY PrimaryEvents.event", $currentEvent, $_SESSION["id"]);
You need to notice that portfolio is not associative array but multidimensional array, so you cannot access it using $portfolio["event"]. You should use $portfolio[0]["event"], $portfolio[1]["event"] and so on.
It's hard to show you exact solution because I don't know how those arrays/database queries should be merged.
EDIT
It seems your query should look like this:
query("SELECT * FROM PrimaryEvents e LEFT JOIN portfolio p ON e.event = p.name WHERE e.unit = ? AND p.id = ? ORDER BY e.event", $unit,$_SESSION["id"]);
EDIT2
I haven't proposed nested loop (as it's now in modified question) because of performance loss.
You're getting closer with your second query, but still confused about what's in each array.
foreach($rowsCompleted as $row)
{
foreach ($portfolio as &$item) // Need to use reference so we can update it
{
if ($item["event"] == $row["name"])
{
//then add our number and date to the array
$item["datecompleted"] = $row["datecompleted"];
$item["number"] = $row["number"];
break;
}
}
}
To avoid the nested loop, it would be better for $portfolio to be an associative array. Change the code for your initial query to use:
//add our stock to the portfolio array
$portfolio[$event["name"]] = $event;
Then the second loop becomes:
foreach($rowsCompleted as $row)
{
$name = $row["name"];
if (isset($portfolio[$name]) {
$portfolio[$name]["datecompleted"] = $row["datecompleted"];
$portfolio[$name]["number"] = $row["number"];
}
}
Example: my current result set:
array(7) {[0]=>array(2)
{ ["class_id"]=>string(1) "1"["class"]=>string(3)"1st"}
{ ["class_id"]=>string(1) "2"["class"]=>string(3)"2nd"}
{ ["class_id"]=>string(1) "3"["class"]=>string(3)"3rd"}
I want a new result set as :
array(7) {[0]=>array(2)
{ ["new_id"]=>string(1) "1"["new_class"]=>string(3)"1st"}
{ ["new_id"]=>string(1) "2"["new_class"]=>string(3)"2nd"}
{ ["new_id"]=>string(1) "3"["new_class"]=>string(3)"3rd"}
I dont want this to affect the column names in my database. only the result set.
Show us your query.. If you're doing, for example, the following query:
SELECT class_id, class FROM table;
Change it to this:
SELECT class_id AS new_id, class AS new_class FROM table;
Changing it in the query is hands-down the best way to do it, as you're not having to do any extra work within PHP, however you could also amend them in PHP, of course.
// where $resultset is your original results..
foreach ($resultset as &$result) {
$result_ = array('new_id' => $result['class_id'], 'new_class' => $result['class']);
$result = $result_;
}
Note that neither of these methods would affect your database columns. The only way to do that would be via an ALTER|MODIFY TABLE statement.
try this
function rename_key(&$array, $oldkey, $newkey) {
// remember here we send value by reference using `&`
if(array_key_exists($oldkey,$array))
{
$array[$newkey] = &$array[$oldkey];
unset($array[$oldkey]);
}
return $array;
}
foreach($input as $k)
{
rename_key($k, 'class_id', 'new_id');
rename_key($k, 'class', 'new_class');
$output[]=$k;
}
echo "<pre>";
print_r ($output);
In foreach cycle. Create a new array with needed to you colums from existing result set.
The goal of this code, is to get all brands for all stores into one array, and output this to the screen. If a brand exists in multiple stores, it will only be added once.
But I feel I have too many for loops, and that it might choke the CPU on heavy traffic.
Is there a better solution to this?
function getBrands($stores, $bl)
{
$html = "";
//Loop through all the stores and get the brands
foreach ($stores as $store)
{
//Get all associated brands for store
$result = $bl->getBrandsByStore($store['id']);
//Add all brands to array $brands[]
while ($row = mysql_fetch_array($result))
{
//If this is the first run, we do not need to check if it already exists in array
if(sizeof($brands) == 0)
{
$brands[] = array("id" => $row['id'], "name" => $row['name']);
}
else
{
// Check tosee if brand has already been added.
if(!isValueInArray($brands, $row['id']))
$brands[] = array("id" => $row['id'], "name" => $row['name']);
}
}
}
//Create the HTML output
foreach($brands as $brand)
{
$url = get_bloginfo('url').'/search?brandID='.$brand['id'].'&brand='.urlSanitize($brand['name']);
$html.= ''.$brand['name'].', ';
}
return $html;
}
//Check to see if an ID already exists in the array
function isValueInArray($values, $val2)
{
foreach($values as $val1)
{
if($val1['id'] == $val2)
return true;
}
return false;
}
From your comment, you mention "Guide table has X stores and each store has Y brands". Presumably there's a "stores" table, a "brands" table, and a "linkage" table, that pairs store_id to brand_id, in a one-store-to-many-brands relationship, right?
If so, a single SQL query could do your task:
SELECT b.`id`, b.`name`
FROM `stores` s
LEFT JOIN `linkage` l
ON l.`store`=s.`id`
LEFT JOIN `brands` b
ON b.`id`=l.`brand`
GROUP BY b.`id`;
That final GROUP BY clause will only show each brand once. If you remove it, you could add in the store ID and output the full list of store-to-brand associations.
No need to loop through two sets of arrays (one to build up the array of brands, and then one to make the HTML). Especially since your helper function does a loop through -- use the array_key_exists function and use the ID as a key. Plus you can use the implode function to join the links with ', ' so you don't have to do it manually (in your existing code you'd have a comma on the end you'd have to trim off). You can do this without two sets of for loops:
function getBrands($stores, $bl)
{
$brands = array();
//Loop through all the stores and get the brands
foreach ($stores as $store)
{
//Get all associated brands for store
$result = $bl->getBrandsByStore($store['id']);
//Add all brands to array $brands[]
while ($row = mysql_fetch_array($result))
{
if (!array_key_exists($row['id'])
{
$url = get_bloginfo('url') . '/searchbrandID=' .
$brand['id'] . '&brand=' . urlSanitize($brand['name']);
$brands[$row['id']] .= '<a href="' . $url . '" id="' .
$brand['id'] . '" target="_self">' .
$brand['name'] . '</a>';
}
}
}
return implode(', ', $html);
}
That will get you the same effect a little faster. It's going to be faster because you used to loop through to get the brands, and then loop through and build up the HTML. Don't need to do that as two separate loops so it all at once and just store the HTML as you go along. Plus since it's switched to use array_key_exists, instead of the helper you wrote that checks by looping through yet again to see if a brand is in there, you'll see more speed improvements. Hashmaps are nice like that because each element in the hashmap has a key and there are native functions to see if a key exists.
You could further optimize things by writing a better SQL statement with a distinct filter to make it so you don't have to do a while inside a foreach.
How are your tables designed? If you had a store table, a brand table, and a link table that had the relationship between stores and brands, you could just pull in the list of brands from the brand table in one query and not have to do any other logic.
Design your tables so they easily answer the questions you need to ask.
If you need to get all the brands for a certain set of stores then you should consider using a query crafted to do that instead of iterating through all the stores and getting the separate pieces of information.