Why foreach enters into if only on first loop? - php

If I loop through foreach loop only on first time it enters into if and gets variable values, so each next time it still have old values. why?
If I print_r($i) and kill it responds:
A0A0A0A0A0A0A0A0A0A0A0A0A0A0TXTTXT16
Real amount is end of it(16). So that means it loops 16 times through loop but into if enters only on first loop of if $type changes. So $type doesn't get new value each time it runs through loop.
Code I have:
$recordTypes = array('CnameRecord', 'ARecord', 'MxRecord', 'TxtRecord');
foreach ($recordTypes as $type) {
$modelName = $type::model()->tableName();
$record = $type::model()->findAllbySql("SELECT * FROM $modelName WHERE vhost_id LIKE $id");
if ($record) {
foreach ($record as $key=>$rec) {
if ($type == 'ARecord'){
$type = 'A' + $i;
$hostname = $rec['sub_vhost_name'];
$points_to = $rec['points_to'];
$ttl = $rec['ttl'];
} else if ($type == 'CnameRecord') {
$type = 'CNAME';
$hostname = $rec['hostname'];
$points_to = $rec['points_to'];
$ttl = $rec['ttl'];
} else if ($type == 'MxRecord') {
$type = 'MX';
$priority = $rec['priority'] . ' ';
$points_to = $rec['points_to'];
$ttl = $rec['ttl'];
$hostname = $rec['host'];
} else if ($type == 'TxtRecord') {
$type = 'TXT';
$hostname = $rec['hostname'];
$points_to = '"' . $rec['txt_value'] . '" ';
$ttl = $rec['ttl'];
}
$i++;
print_r($type);
$custom_content = $hostname . ' ' . $ttl . ' ' . 'IN' . ' ' . $type . ' ' . $priority . $points_to . "\n";
}
}
}
print_r($i);die;

you are using:
foreach ($recordTypes as $type) { ...
And inside the foreach you're modifying the "type" var, so in the next loops through $record, you'll fail any if statement.
Change the $type var (inside if statements) to another var name and try again.

Related

Array_push in for loop giving null response

Hello I am trying to push in an array using array_push but I am getting the value of the first index then after that all I am getting a null response, I am not getting where I have done a mistake.I am getting the values properly but in array_push there is some mistake which is in for loop.
Here is my code :
function actioncouponcsv_download() {
$this->layout = false;
foreach (Yii::app()->log->routes as $route) {
if ($route instanceof CWebLogRoute || $route instanceof CFileLogRoute || $route instanceof YiiDebugToolbarRoute) {
$route->enabled = false;
}
}
$dateRange = json_decode($_POST['dateRange'], true);
$start = $dateRange['start'];
$end = $dateRange['end'];
$validity = $_POST['validity'];
$limit = isset($_REQUEST['limit']) && trim($_REQUEST['limit']) ? $_REQUEST['limit'] : 0;
$studio_id = Yii::app()->user->studio_id;
if (isset($_GET['type']) && intval($_GET['type']) ==2) {
$couponobj = new CouponSubscription();
$getcouponobj = $couponobj->getcoupon_data($studio_id,$start,$end,$validity);
$k = 0;
$title_addon = "\t" . "Discount Cycle" . "\t" . "Extend free trail";
$data_addon = "\t" . $getcouponobj[$k]['discount_multiple_cycle'] . "\t" . $getcouponobj[$k]['extend_free_trail'];
} else {
$title_addon = "";
$data_addon = "";
$couponobj = new Coupon();
$getcouponobj = $couponobj->getcoupon_data($studio_id,$limit,1);
}
//$Coupon = Coupon::model()->find('studio_id=:studio_id', array(':studio_id' => $studio_id));
$dataCsv = '';
if ($getcouponobj) {
$headings = "Sl no" . "\t" . "Coupon" . "\t" . "Coupon Type" . "\t" . "Used by a single user" . "\t" . "Valid" . "\t" . "Used" . "\t" . "User" .$title_addon. "\t" . "Used Date". "\t" . "Content Category". "\t" . "Content"."\n";
$i = 1;
$dataCSV[] = Array();
$j = 0;
for ($k = 0; $k < count($getcouponobj); $k++) {
$userList = '-';
if ($getcouponobj[$k]['used_by'] != '0') {
if ($getcouponobj[$k]['coupon_type'] == 1) {
$userList = '';
$userIdList = explode(",", $getcouponobj[$k]['used_by']);
foreach ($userIdList as $userIdListKey => $userIdListVal) {
if ($userIdListKey == 0) {
$userList .= Yii::app()->webCommon->getuseremail($userIdListVal);
} else {
$userList .= " | " . Yii::app()->webCommon->getuseremail($userIdListVal);
}
}
} else {
$userList = Yii::app()->webCommon->getuseremail($getcouponobj[$k]['used_by']);
}
}
if($getcouponobj[$k]['is_all']!=1){
if($getcouponobj[$k]['content_category']==1){
$cont_cat = "Digital";
$content_str = Coupon::model()->getContentInfo($getcouponobj[$k]['specific_content']);
$cont_str = $content_str;
}else if($getcouponobj[$k]['content_category']==2){
$cont_cat = "Physical";
$content_str = Coupon::model()->getContentInfoPhysical($getcouponobj[$k]['specific_content']);
$cont_str = $content_str;
}else{
$cont_cat = "All";
$cont_str = "All";
}
}else{
$cont_cat = "All";
$cont_str = "All";
}
#echo $getcouponobj[$k]['coupon_code'];
array_push($dataCSV[$j],$i);
array_push($dataCSV[$j],$getcouponobj[$k]['coupon_code']);
array_push($dataCSV[$j],(($getcouponobj[$k]['coupon_type'] == 1) ? 'Multi-use' : 'Once-use'));
array_push($dataCSV[$j],(($getcouponobj[$k]['user_can_use'] == 1) ? 'Multiple times' : 'Once'));
array_push($dataCSV[$j],(($getcouponobj[$k]['used_by'] == 0) ? 'Yes' : 'No'));
array_push($dataCSV[$j],(($getcouponobj[$k]['used_by'] == 0) ? '-' : 'Yes'));
array_push($dataCSV[$j],$userList);
array_push($dataCSV[$j],$getcouponobj[$k]['discount_multiple_cycle']);
array_push($dataCSV[$j],$getcouponobj[$k]['extend_free_trail']);
array_push($dataCSV[$j],(($getcouponobj[$k]['cused_date'] == 0) ? '-' : $getcouponobj[$k]['cused_date']));
array_push($dataCSV[$j],$cont_cat);
array_push($dataCSV[$j],$cont_str);
$j++;
//$dataCsv .= $i . "\t" . $getcouponobj[$k]['coupon_code'] . "\t" . (($getcouponobj[$k]['coupon_type'] == 1) ? 'Multi-use' : 'Once-use') . "\t" . (($getcouponobj[$k]['user_can_use'] == 1) ? 'Multiple times' : 'Once') . "\t" . (($getcouponobj[$k]['used_by'] == 0) ? 'Yes' : 'No') . "\t" . (($getcouponobj[$k]['used_by'] == 0) ? '-' : 'Yes') . "\t" . $userList .$data_addon. "\t" . (($getcouponobj[$k]['cused_date'] == 0) ? '-' : $getcouponobj[$k]['cused_date'])."\t" .$cont_cat ."\t".$cont_str."\n";
$i = $i+1;
}
}
print_r(json_encode($dataCSV));
}
PS: I am getting the values. Any help will be highly appreciated.
Well, first thing i see wrong is the way you declare your array:
$dataCSV[] = Array();
$array[] = Means that you are adding a new value to an existing array. To declare your array you should use
$dataCSV = array();
Also, this code:
array_push($dataCSV[$j],$i);
means that you are adding a new value to your $dataCSV[$j] array, but this is never declared as an array, so first thing would be to do
$dataCSV[$j] = new array();
Your code is really long and complicated, those are only examples of issues i see in there.

foreach sort results from database

I have 9 blocks, and I want sort it by last news added.
I have code:
$projects = Projects::find(['conditions' => 'active = 1', 'order' => 'id DESC']);
$itemsps = [];
foreach($projects as $project) {
if(!$project->{'link_' . $lang. ''}) continue;
$itemsp['title_md'] = $project->title_md;
$itemsp['title_ru'] = $project->title_ru;
$itemsp['link'] = 'http://'.$_SERVER['SERVER_NAME']. '/' . $lang . '/' . $project->{'link_' . $lang. ''};
$category = Categories::findFirst('alias = ' . "'$project->link_md'" . ' OR alias_ru = ' . "'$project->link_ru'");
$lastCat = NewsCategories::find('categories_id = ' . $category->id)->getLast();
if($lastCat === false) continue;
$lastImage = 'uploads/' . $lastCat['news_id'] . '.jpg';
$itemsp['image'] = $lastImage;
$itemsps[] = $itemsp;
}
How I can order by last records of:
$lastCat = NewsCategories::find('categories_id = ' . $category->id)->getLast();
Results in my array:
itemsps
I dont know your DB but i bet you can achive your goal with just one query and some tables joins.
Please take some time to understand phalcon models
If you still want to use that format you could use array_multisort() to sort the array:
$projects = Projects::find(['conditions' => 'active = 1', 'order' => 'id DESC']);
$itemsps = [];
foreach($projects as $project) {
if(!$project->{'link_' . $lang. ''}) continue;
$itemsp['title_md'] = $project->title_md;
$itemsp['title_ru'] = $project->title_ru;
$itemsp['link'] = 'http://'.$_SERVER['SERVER_NAME']. '/' . $lang . '/' . $project->{'link_' . $lang. ''};
$category = Categories::findFirst('alias = ' . "'$project->link_md'" . ' OR alias_ru = ' . "'$project->link_ru'");
$lastCat = NewsCategories::find('categories_id = ' . $category->id)->getLast();
$itemsp['lastCat'] = $lastCat; //ADD THIS
if($lastCat === false) continue;
$lastImage = 'uploads/' . $lastCat['news_id'] . '.jpg';
$itemsp['image'] = $lastImage;
$itemsps[] = $itemsp;
}
//ADD THE CODE BELOW
$lastCat_array = array();
foreach ($itemsps as $key => $row)
{
$lastCat_array[$key] = $row['lastCat'];
}
array_multisort($lastCat_array, SORT_DESC, $itemsps);
print_r($itemsps);

Build one object from foreach loop

I want to take an array I build from a result set, encode it and then put it into a single object. My problem is I am making a lot of objects, but I want all my data to be in one object. The problem is that I echo out multiple objects from my json encode on my foreach loop. How would I take all that data I get out of that foreach loop and put it into one object? Any help is appreciated. Below is my code. Basically, what I need is this.
{"item1":"itemdata","category":"mycategory"}
but all in one object. I don't want multiple {} {} {}
$counter = 0;
$itemID = '';
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build['bid'] = $bid;
$build['id'] = $ID;
$build['item_desc'] = $description;
}
$itemID = $result['item_id'];
$counter++;
echo json_encode($build);
}
Create an array to hold the smaller arrays before your loop.
$fullData = array();
Then, inside your loop after you finish your build array add the build array to the fullData array.
$fullData[] = $build;
remove your current json_encode() and then, outside the loop.
echo json_encode($fullData);
This is what it would be changed to:
<?php
$counter = 0;
$itemID = '';
$fullData = array();
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build['bid'] = $bid;
$build['id'] = $ID;
$build['item_desc'] = $description;
}
$itemID = $result['item_id'];
$counter++;
$fullData[] = $build;
}
echo json_encode($fullData);
?>
Change this
$counter = 0;
$itemID = '';
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build['bid'] = $bid;
$build['id'] = $ID;
$build['item_desc'] = $description;
}
$itemID = $result['item_id'];
$counter++;
echo json_encode($build);
}
To
$counter = 0;
$itemID = '';
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build[] = array('bid'=>$bid,'id'=>$ID,'item_desc'=>$description);
}
$itemID = $result['item_id'];
$counter++;
}
echo json_encode($build);

How To Change Numbers Based On Results

I have a follow up question on something I got help with here the other day (No Table Three Column Category Layout).
The script is as follows:
$res = mysql_query($query);
$system->check_mysql($res, $query, __LINE__, __FILE__);
$parent_node = mysql_fetch_assoc($res);
$id = (isset($parent_node['cat_id'])) ? $parent_node['cat_id'] : $id;
$catalist = '';
if ($parent_node['left_id'] != 1)
{
$children = $catscontrol->get_children_list($parent_node['left_id'], $parent_node['right_id']);
$childarray = array($id);
foreach ($children as $k => $v)
{
$childarray[] = $v['cat_id'];
}
$catalist = '(';
$catalist .= implode(',', $childarray);
$catalist .= ')';
$all_items = false;
}
$NOW = time();
/*
specified category number
look into table - and if we don't have such category - redirect to full list
*/
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE cat_id = " . $id;
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$category = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)
{
// redirect to global categories list
header ('location: browse.php?id=0');
exit;
}
else
{
// Retrieve the translated category name
$par_id = $category['parent_id'];
$TPL_categories_string = '';
$crumbs = $catscontrol->get_bread_crumbs($category['left_id'], $category['right_id']);
for ($i = 0; $i < count($crumbs); $i++)
{
if ($crumbs[$i]['cat_id'] > 0)
{
if ($i > 0)
{
$TPL_categories_string .= ' > ';
}
$TPL_categories_string .= '' . $category_names[$crumbs[$i]['cat_id']] . '';
}
}
// get list of subcategories of this category
$subcat_count = 0;
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . $id . " ORDER BY cat_name";
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$need_to_continue = 1;
$cycle = 1;
$column = 1;
$TPL_main_value = '';
while ($row = mysql_fetch_array($result))
{
++$subcat_count;
if ($cycle == 1)
{
$TPL_main_value .= '<div class="col'.$column.'"><ul>' . "\n";
}
$sub_counter = $row['sub_counter'];
$cat_counter = $row['counter'];
if ($sub_counter != 0)
{
$count_string = ' (' . $sub_counter . ')';
}
else
{
if ($cat_counter != 0)
{
$count_string = ' (' . $cat_counter . ')';
}
else
{
$count_string = '';
}
}
if ($row['cat_colour'] != '')
{
$BG = 'bgcolor=' . $row['cat_colour'];
}
else
{
$BG = '';
}
// Retrieve the translated category name
$row['cat_name'] = $category_names[$row['cat_id']];
$catimage = (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '';
$TPL_main_value .= "\t" . '<li>' . $catimage . '' . $row['cat_name'] . $count_string . '</li>' . "\n";
++$cycle;
if ($cycle == 7) // <---- here
{
$cycle = 1;
$TPL_main_value .= '</ul></div>' . "\n";
++$column;
}
}
if ($cycle >= 2 && $cycle <= 6) // <---- here minus 1
{
while ($cycle < 7) // <---- and here
{
$TPL_main_value .= ' <p> </p>' . "\n";
++$cycle;
}
$TPL_main_value .= '</ul></div>'.$number.'
' . "\n";
}
I was needing to divide the resulting links into three columns to fit my html layout.
We accomplished this by changing the numbers in the code marked with "// <---- here".
Because the amount of links returned could be different each time, I am trying to figure out how to change those numbers on the fly. I tried using
$number_a = mysql_num_rows($result);
$number_b = $number_a / 3;
$number_b = ceil($number_b);
$number_c = $number_b - 1;
and then replacing the numbers with $number_b or $number_c but that doesn't work. Any ideas?
As mentioned before, you can use the mod (%) function to do that.
Basically what it does is to get the remainder after division. So, if you say 11 % 3, you will get 2 since that is the remainder after division. You can then make use of this to check when a number is divisible by 3 (the remainder will be zero), and insert an end </div> in your code.
Here is a simplified example on how to use it to insert a newline after every 3 columns:
$cycle = 1;
$arr = range (1, 20);
$len = sizeof ($arr);
for ( ; $cycle <= $len; $cycle++)
{
echo "{$arr[$cycle - 1]} ";
if ($cycle % 3 == 0)
{
echo "\n";
}
}
echo "\n\n";

multiple shorten url's issue

i have a code to shorten multiple links but that code ( with an Optional Suffix ) the code is work from the second link only:
$url_to_shorten = $_POST[links];
$ownshuff = $_POST[shuff];
$theurls = explode("\n",$url_to_shorten);
foreach($theurls as $urlmulti){
shortcreate($urlmulti,$shuffss,$ownshuff);
}
here is an example :
my links are
http://www.123.com
http://www.1234.com
http://www.1235.com
and my Suffix is : ( Hello_Man ).
with the above code it prints
http://www.mysite.com/IUo
http://www.mysite.com/kOl-Hello_Man
http://www.mysite.com/Rww-Hello_Man
and it not print the Suffix for the first link.
the shortcreate function is :
function shortcreate($url_long, $Suffix, $ownshuf){
global $db;
$chars = $Suffix;
while (!shortisUnique($chars)) {
if ($ownshuf != "") {
$chars = shortgenerate_chars() . "-" . $ownshuf;
}
else {
$chars = shortgenerate_chars();
}
}
$url = $url_long;
$url = trim($url);
$url = mysql_real_escape_string($url);
if (!shortisThere($url)) {
$q = "INSERT INTO `shorturls` (url, unique_chars) VALUES ('" . $url . "', '" . $chars . "')";
//echo $q;
$r = $db->query($q);
if (mysql_affected_rows()):
$q = "SELECT * FROM `shorturls` WHERE `url`='" . $url . "'";
$r = $db->query($q);
$row = $db->fetch($r);
$the_url = SITE_URL . "" . $row[2];
echo "$the_url\n";
else:
$the_url = NULL;
return false;
endif;
}
else {
$q = "SELECT * FROM `shorturls` WHERE `url` = '" . $url . "'";
$r = mysql_query($q);
$row = mysql_fetch_row($r);
$the_url = SITE_URL . "" . $row[2];
echo "$the_url\n";
}
}
i need that code to work for all the links. any help
regards
I guess that the problem is in the next block of code:
$chars = $Suffix;
while (!shortisUnique($chars)) {
if ($ownshuf != "") {
$chars = shortgenerate_chars() . "-" . $ownshuf;
}
else {
$chars = shortgenerate_chars();
}
}
You give the $chars variable the value of the suffix and you check if it's unique (guess not because it's getting into the loop) and that condition of $ownshuf != "" returns false from some reason (consider to share with us what's that parameter's value), otherwise the output of $chars would return a string with "-".
REMINDER: Share with us what's that parameter's value

Categories