PHP Loop to loop through page ID and locations - php

I am trying to build a loop to show different location names based on the page ID. I am trying a for loop, but not sure how to get the 2 results, I tried a foreach, but still got lost.
$location = array( "Frisco" => "1507", "McKinney" => "1509");
$count = count($location);
for($i = 0; $i < $count; $i++){
if(is_page($location[$i])) {
$location = "";
}
}
Need results =
// Add Shortcode
function dynamicLocation(){
if(is_page('1')){
$location = "McKinney";
}
else if(is_page()){
$location....
}
}

Forget for, use foreach:
foreach ($location as $key=>$value){
//here $key is the location and $value is the ID
//e.g. $key="Frisco", $value="1507"
}

Related

how to sort an array in descending order in php

Newly-entered products are displayed in the last row. If there is a large amount, it is difficult to see at the bottom. How can I change the new display to the top. Thank you!
$barcodes_ary = explode(',', $barcodes);
$barcodes_hash = array ();
foreach ($barcodes_ary as $b) {
if (array_key_exists($b, $barcodes_hash)) {
$barcodes_hash[$b] += 1;
} else {
$barcodes_hash[$b] = 1;
}
}
foreach ($barcodes_hash as $b => $amount) {
if ($barcodes_ary == array(''))continue;
$ary = get_sql("SELECT * FROM Products WHERE Barcode='$b' Order by ProductName");
if ( count($ary) == 0 ) {
continue;
}
$pid = $ary[0]['ProductID'];
$pn = $ary[0]['ProductName'];
$unit = $ary[0]['UnitID'];
$ary2 = get_sql("SELECT UnitName FROM Units WHERE UnitID = '$unit'");
$unit = $ary2[0]['UnitName'];
?>
<TR>
<TD><? echo "$pn"; ?></TD>
<TD>
<INPUT TYPE=hidden NAME=productid<?=$pid?> VALUE='<?=$pid?>'>
<?
$candidates = array();
for($i=1; $i <= DropDownMaxValue; $i++) {
$candidates[]=$i;
}
//update
I use another way to solve the problem. Just display the same product.
function push_barcode() {
// alert('barcode pushing');
b = document.form1.barcode;
bs = document.form1.barcodes;
if (bs.value == "") {
bs.value = b.value;
} else { // ?? 111,333,444,... ???
bs.value = b.value;
}
}
Okay, you should be able to get the count using the keys values returned in reverse in brackets with the array.
Try the following and see if it works for you...
$ProductName = $ary[0]['ProductName'];
//--> get the count of your array
$count = count($ProductName);
//--> define an output variable to hold values
$output = null;
$i = 0;
//--> reduce count by one as key values start at 0 and count starts at 1
$count = $count - 1;
//--> subtraction and addition of $count by one to reduce warning
//--> of `undefined offset` for index on mismatched key values
while($count + 1){
//--> concatenate the values into a variable for display
$output .= $ProductName[$count];
//--> or push the reversed values back into an array
$product_name[$i] = $ProductName[$count];
//--> $product_name should now hold your values in reverse use a foreach
// use a foreach to display values in your table
$count--;
$i++;
}

get_category_parents to array wordpress

Ok So I'm using wordpress and PHP.
Basicly I get a chosen category from a dropdown menu. I then find it's parents.
But then comes the part where I seem to fail. The output of $parents is a string with the names instead of the ID's.
So I try to get each word from the string into an array.
And loop through them and convert them to their ID number.
I commented out where it doesnt seem to work. What am I doing wrong?
//Create array
$categoriesArray = [];
//Get choice from wp-dropdown
$selected_val = $_POST['cat'];
//Get parents from choice divided by (this seems to output a string)
$parents = get_category_parents( $selected_val, true, ',' );
/*
//Make array from string
$categoriesArray = explode(",",$parents);
for ($i = 0; $i < count($categoriesArray); $i++) {
{
$categoriesArray[$i] = get_cat_ID($categoriesArray[$i]);
}
*/
//the array should look something like this.
//$categoriesArray = ["21","44"];
try this,
function get_level($cat, $level = 0)
{
if ($cat->category_parent == 0) {
return $level;
} else {
$level++;
$cat = get_category($cat->category_parent);
return get_level($cat, $level);
}
}
if (is_category()) {
$cat = get_query_var('cat');
$your_cat = get_category($cat);
echo get_level($your_cat);
}
It had to do with the name of the category. I needed to use the slug instead of the name.
Here is my code that works. I can now make a new post and give it a category with their parents included!
//Create array
$categoriesArray = [];
//Get choice from wp-dropdown
$selected_val = $_POST['cat'];
//Get parents from choice divided by ,
$parents = get_category_parents( $selected_val, true, ',',false);
//Make array from string
$categoriesArray = explode(",",$parents);
for ($i = 0; $i < count($categoriesArray); $i++)
{
$categoriesArray[$i] = get_cat_ID($categoriesArray[$i]);
}

Count groups in loop foreach

My Script :
<?php
$values='Product1,54,3,888888l,Product2,54,3,888888l,';
$exp_string=explode(",",$values);
$f=0;
foreach($exp_string as $exp_strings)
{
echo "".$f." - ".$exp_string[$f]." ";
if ($f%3==0)
{
print "<br><hr><br>";
}
$f++;
}
?>
With this code i want show data inside loop, the idea it´s show all information in groups the elements in each group it´s 4 elements and must show as this :
Results :
Group 1 :
Product1,54€,3,green
Group 2:
Product2,56€,12,red
The problem it´s i don´t know why, don´t show as i want, and for example show separate some elements and not in group, thank´s , regards
It looks like you are trying to combine elements of a for loop and a foreach loop.
Here is an example of each, pulled from the php manual:
For Loop
for($index = 0, $index < size($array), $index++ {
//Run Code
//retrieve elements from $array with $array[$index]
}
Foreach
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
It's hard for me to understand what your input looks like. If you post an example of $exp_strings, I could be of better assistance. But from the sound of your question, if $exp_strings is multidimensional if you need to loop through groups of items, you could try nesting one loop inside another loop like so:
$groups_of_data = array(array(...), array(...), array(...));
for($i = 0, $i < size($groups_of_data), $i++) {
$group = $i;
for($j = 0, $j < size($groups_of_data[$i]), $j++) {
// print out data related to group $i
}
}
This is really all guesswork on my part though as I can't see what your input string/array is. Can you post that? Maybe I can be of more help.
here is code i worked out. it was kind of since i did't know what object $exp_string is. if it's a string you should tokenize it, but i think it's array from database. there was another problem, with your code where it tries to output $exp_string[$f] it should be $exp_strings what changes in the loop.
my code
$exp_string=array("Product"=>54,"price"=>3,"color"=>"green");
$f=0;
foreach($exp_string as $key => $exp_strings)
{
if($f%3==0)
{
print "<br><hr><br>";
echo "Product ".$exp_strings."<br> ";
}
else if($f%3==1)
{
echo "Price ".$exp_strings."<br> ";
}
else if($f%3==2)
{
echo "Color ".$exp_strings."<br> ";
}
$f++;
}
hope it's any help, maybe not what you wanted.
$values='Product1,1,2,3,Product2,1,2,3,Product3,1,2,3';
$products = (function($values) {
$exp_string = explode(',', $values);
$products = [];
for ($i=0; $i+3<count($exp_string); $i+=4) {
$product = [
'title' => $exp_string[$i],
'price' => $exp_string[$i+1],
'color' => $exp_string[$i+2],
'num' => $exp_string[$i+3],
];
array_push($products, $product);
}
return $products;
})($values);
/* var_dump($products); */
foreach($products as $product) {
echo "{$product['title']},{$product['price']},{$product['color']},{$product['num']}<br>";
}

Move information from one variable to another (same page)

Since i have many diffrent workers on my workkey and i just want to print every work once. I Though of doin a check like this.
At the end of the loop i wanna save the value from workkey. So before every print i will check, If the new workkey is diffrent from the last one = Dont print.
$counter = 0;
while(db2_fetch_row($queryexe)) {
$work = db2_result($queryexe, 'workkey');
$fname = db2_result($queryexe, 'fname');
$lname = db2_result($queryexe, 'lname');
if ($workkey != $saveworkkey){
$counter = 0;
}
if ($counter < 1){
print ( some stuff)
print ( some stuff)
print ( some stuff)
}
$workkey = $saveworkkey;
$counter++;
}
What I do to solve the issue is to add all values to an array with the key as array key. This way, even if there are duplicates they will overwrite eachother.
$workers = array()
while ($record = db2_fetch_row($queryexe)) {
$workers[$record['workkey']] = $record;
}
To print your values you can simply foreach
foreach ($workers as $worker) {
// print worker
}

loop through an array and show results

i m trying to do a loop but get stacked ,
i have a function that convert facebook id to facebook name , by the facebook api. name is getName().
on the other hand i have an arra with ids . name is $receivers.
the count of the total receivers $totalreceivers .
i want to show names of receivers according to the ids stored in the array.
i tried every thing but couldnt get it. any help will be appreciated . thanks in advance.
here is my code :
for ($i = 0; $i < $totalreceivers; $i++) {
foreach ( $receivers as $value)
{
echo getName($receivers[$i]) ;
}
}
the function :
function getName($me)
{
$facebookUrl = "https://graph.facebook.com/".$me;
$str = file_get_contents($facebookUrl);
$result = json_decode($str);
return $result->name;
}
The inner foreach loop seems to be entirely redundant. Try something like:
$names = array();
for ($i = 0; $i < $totalReceivers; $i++) {
$names[] = getName($receivers[$i]);
}
Doing a print_r($names) afterwards should show you the results of the loop, assuming your getNames function is working properly.
Depending of the content of the $receivers array try either
foreach ($receivers as $value){
echo getName($value) ;
}
or
foreach ($receivers as $key => $value){
echo getName($key) ;
}

Categories