How to use variables within a PHP array - php

I have this code:
foreach ($row as $result) {
if (empty($row[28])) {
$string28 = '';
} else {
$string28 = '<div class="add_img">
<h1>Connexion</h1>
<img src="images/' . $row[28] . '.jpeg">
</div>';
}
}
foreach ($row as $result) {
if (empty($row[30])) {
$string30 = '';
} else {
$string30 = '<div class="add_img">
<h1>Fixation</h1>
<img src="images/' . $row[30] . '.jpeg">
</div>';
}
}
foreach ($row as $result) {
if (empty($row[31])) {
$string31 = '';
} else {
$string31 = '<div class="add_img">
<h1>Schéma</h1>
<img src="images/' . $row[31] . '.jpeg">
</div>';
}
}
$applications = array($string28, $string30, $string31);
if (empty($applications)) {
$vide = "<h1>Pas D'Application Pour Ce Produit</h1>";
}
What I want to say here is: if all the variables are empty then show me this:
Pas D'Application Pour Ce Produit (Translated: No application for this product)
But When I use the print_r function it tells to me that the array has no data to deal with.
Please I need Help.
And Thanks to all in advanced

You are not accessing your rows correctly in your foreach loops. When using foreach($row as $result) you need to refer to the array element as $result, not row. If you need to identify a specify array key you can specify that by using foreach($row as $key => $result).
For example, in your first loop you should use this:
$string28 = ''; //Initialize your variable so can be used after the foreach loop exits
foreach ($row as $key => $result) {
if($key == 28 && empty($result[$key]) {
$string28 = '';
} else {
$string28 = '<div class="add_img"><h1>Connexion</h1><img src="images/'.$result[$key].'.jpeg">
}
}
Repeat for the other loops in your script.
EDIT
Yes, you can setup one foreach loop that will go through all your variables and create variables for you. Based on your question, if you don't have any apps an error message shows. What you may wish to do is simply set a flag based on that criteria. You could do do this like so:
$noApps = true;
$applications = array();
foreach($row as $key => $result) {
if(isset($result[$key]) && empty($result[$key])) {
$applications[$key] = '<div class="add_img"><h1>Connexion</h1><img src="images/'.$result[$key].'.jpeg'>;
$noApps = false;
}
}
if($noApps) {
echo "<h1>Pas D'Application Pour Ce Produit</h1>";
} else {
print_r($applications); //For viewing/debugging purposes
}

Your foreach loops is wrong. You are using the whole array instead of the elements as is used within a foreach loop.
You have used
foreach ($row as $result) {
//You are doing something with $row
}
Instead correct usage is
foreach ($row as $result) {
//Do something with $result
}
Hope it helps :)

Your design looks bad. You are essentially repeating the same functionality 3 times.
Your while loops don't work because you're using $row in them, instead of the $result variable.
The second point is, The $string28, $string30, $string31 are created as local variables within the if conditions you have written in the while loops. Once the control exits the "if" loops these variables are nothing. To solve this problem, try initializing these to empty data like$string28 ="" at the beginning point of your code.
However, I would recommend you to look at the structure of your code first.

Related

Outputting odd and even number in array

Using below array, i'm trying to use foreach loop to iterate through each item. Then i need to apply if condition to check if the given number is even and odd. I also need to create two arrays one for even and one for odd and push each number in their respective category.
So i have done this so far:
These are the two arrays i created to push through the values to.
}
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
$array_odd = [];
$array_even = [];
foreach ($numbers as $value)
{
if (value %2 == 0)
{
$array_even = $value;
echo $array_even;
}
else
{
$array_odd = $value;
echo $array_odd;
}
I'd like to know if i'm using the correct solution or are there major errors im committing?
It will surely work like charms.
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
$array_odd = [];
$array_even = [];
foreach ($numbers as $value)
{
if ($value %2 == 0)
{
$array_even[] = $value;
}
else
{
$array_odd[] = $value;
}
}
echo "<pre>";
print_r($array_odd);
echo "<pre>";
print_r($array_even);

Filtering an array with foreach and for loop

I'm pulling data from mssql database into an array called
$results2
I need to echo out each 'Item' only one time, so this example should only echo out:
"52PTC84C25" and "0118SGUANN-R"
I can do this easily with:
$uniqueItems = array_unique(array_map(function ($i) { return $i['ITEM']; }, $results2));
The issue is when i try to echo out the other items associated with those values. I'm not sure how to even begin on echoing this data. I've tried:
foreach($uniquePids as $items)
{
echo $items."<br />";
foreach($results2 as $row)
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
}
}
This returns close to what I need, but not exactly:
This is what I need:
Assuming your resultset is ordered by ITEM...
$item = null; // set non-matching default value
foreach ($results2 as $row) {
if($row['ITEM'] != $item) {
echo "{$row['ITEM']}<br>"; // only echo first occurrence
}
echo "{$row['STK_ROOM']}-{$row['BIN']}<br>";
$item = $row['ITEM']; // update temp variable
}
The if condition in the code will check if the ITEM has already been printed or not.
$ary = array();
foreach($results2 as $row)
{
if(!in_array($row['ITEM'], $ary))
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
$ary[] = $row['ITEM'];
}
}

php second foreach doesn't write out values

I have a problem with displaying my data. I have data in the following
filter_name filter_value
Hard Drize Size 16GB
Hard Drize Size 32GB
Screen Size 7''
Screen Size 8''
And I want to present it like this.
Hard Drize Size
16GB
32GB
Screen Size
7''
8''
What I want in my php code is to check if the filter_name is in the $temp array and if it isn't then add it to $temp array so it won't cause duplicate entries. The problem I'm getting now is when I use the same data to do a second foreach inside the loop I get no data and my sql is correct. So I don't know how to out put the values. With the second foreach it only prints out the first $filter_name["filter_name"] and that all.
php:
if($stmt->rowCount() > 0)
{
$filters = "<div class=\"filters\">
<div class=\"apply-filters\">Filters</div>";
$temp = array();
$stmt->fetch(PDO::FETCH_ASSOC);
foreach($stmt as $filter_name)
{
if(!in_array($filter_name["filter_name"], $temp))
{
$temp[] = $filter_name["filter_name"];
$filters .= "<div class=\"filter-header\">".$filter_name["filter_name"]."</div>";
//second loop here doesn't work with the same data.
// test if filter_name["filter_name"] == second loop second_loop["filter_name"]
// ten write out second_loop["filter_value"] e.g.
foreach($stmt as $filter_value)
{
if($filter_name["filter_name"] == $filter_value["filter_name"])
{
$filters .= $filter_value["filter_value"] ."<br />";
}
}
}
}
$filters .= "</div>";
}
First, do a var_dump of $stmt before the first and second foreach to look at it's form. Perhaps it's not formatted the way you think?
Why don't you loop over $stmt once and in that loop print $stmt['filter_name'] and $stmt['filter_value']? Now you loop $stmt one "extra" time for each iteration of the first foreach. Instead just do a foreach($stmt as $filter) and $filter, being a associative array, should contain filter_name and filter_value for each entry.
You could then move the actual printing outside of the foreach and only construct your array in the loop that should look something like
array("Hard Drive Size" => array("16GB", "32GB"), "Screen Size" => array("7''", "8''"));
Then you could traverse that data structure using
foreach($myArray as $filter_name => $filter_values)
{
// Print filter name header
foreach($filter_values as $filter_value)
{
// print each value of the specific filter
}
}
To build the presented structure you could do something like
...
$filters = array();
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $filter)
{
$filters[$filter['filter_name']][] = $filter['filter_value'];
}
...
Then iterate the $filters structure and print it.
Update:
From your var_dump of $stmt it's clear that $stmt is not your result set. You should assign the result of $stmt->fetch to something. Like $result = $stmt->fetch(PDO::FETCH_ASSOC) and then iterate over $result.
Check
http://php.net/manual/en/pdostatement.fetch.php
http://php.net/manual/en/pdostatement.fetchall.php
i slightly modified your code to fit your needs:
$temp = array();
foreach($stmt as $filter_name)
{
if(!in_array($filter_name["filter_name"], $temp))
{
echo '<b>' . $filter_name['filter_name'] . '</b><br>';
$temp[] = $filter_name["filter_name"];
foreach($stmt as $filter_value)
{
if($filter_name["filter_name"] == $filter_value["filter_name"])
{
echo $filter_value['filter_value'] . '<br>';
}
}
}
}
you can check a working sample here -> http://codepad.viper-7.com/aFD079
You are missing $ before filter_value.
Change
foreach($stmt as filter_value)
To
foreach($stmt as $filter_value)
$stmt->fetch(PDO::FETCH_ASSOC);
foreach($stmt as $filter_name)
may be (i am not sure)
$aaa= $stmt->fetch(PDO::FETCH_ASSOC);
foreach($aaa as $filter_name)
and try
$rows = $stmt->fetch(PDO::FETCH_ASSOC);
$tmp_name='';
$html='';
foreach($rows as $row)
{
if($row['filter_name'] != $tmp_name){
$html .=$row['filter_name'];
}
$html .=$row['filter_value'];
$tmp_name=$row['filter_name'];
}
echo $html;
if($stmt->rowCount() > 0)
{
$filters = "<div class=\"filters\">
<div class=\"apply-filters\">Filters</div>";
$temp = array();
$stmt->fetch(PDO::FETCH_ASSOC);
foreach($stmt as $filter)
$temp[$filter['filter_name']][] = $filter['filter_value'];
foreach($temp as $filter_name => $filter_values)
{
$filters .= "<div class=\"filter-header\">".$filter_name."</div>";
foreach ($filter_values as $value)
$filters .= $filter_value."<br />";
}
$filters .= "</div>";
}

PHP duplicated list

Here is my code to list all category as a list item:
if ($xml) {
foreach($xml->children() as $IRXML) { // SHOW ONLY 5 NEWS ITEMS
foreach($IRXML->children() as $newsrelease) { // EACH NEWSRELEASE IS ONE SUBCHILD
// echo " <div class='news-image'>";
// echo "<img src='/wp-content/themes/bby/images/news-story-01.jpg' alt=''>";
// echo "</div>";
$categories = $newsrelease->Categories;
foreach($categories->children() as $category) {
if ($category != "NA") {
echo "<li class='category ".$category."'>".$category."</li> ";
}
}
}
}
}
What I wanted to do is only to display a category without duplicating it.
$list_cache = array();
if ($xml)
{
foreach($xml->children() as $IRXML)
foreach($IRXML->children() as $newsrelease)
{
$categories = $newsrelease->Categories;
foreach($categories->children() as $category)
{
if ($category != "NA")
{
$print_category = "<li class='category ".$category."'>".$category."</li> ";
if( !in_array($print_category, $list_cache) ) //check if you've stored in previously in this array. In such case, in_array will return true.
{
$list_cache[] = $print_category;
echo $print_category;
}
}
}
}
}
Check out the in_array function from the documentation.
Do you mean you want to display each one only once? If .children() is returning the same child twice, that could be another problem; if it's not something you can change and this is the behavior you're seeing, you could keep an array of category names/ID's, append as you display them, and check the array for duplicates before writing output each time the loop runs.
Assuming there is no way to eliminate the duplicates when generating the XML...that would be more efficient.
You could create an array outside of the loop, and then check to see if a category has already been seen. Example:
$categories = $newsrelease->Categories;
$seen_categories = array();
foreach($categories->children() as $category) {
if ($category != "NA" && !in_array($category,$seen_categories)) {
$seen_categories[]=$category;
echo "<li class='category ".$category."'>".$category."</li> ";
}
}

PHP pass variable to foreach loop from a mySQL result

I need to pass a variable to a foreach loop from a mySQL result.
So I have this code:
$GetClaim = "SELECT * FROM cR_Claimants WHERE memberID = '".$memberID."' AND ParentSubmission ='".$refNumb."'";
$resultGetClaim=mysql_query($GetClaim) or die("Error select claimants: ".mysql_error());
while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
$name = $rowGetClaim['Name'];
$city = $rowGetClaim['city'];
$region = $rowGetClaim['region'];
}
Now I need to pass the variable to the foreach
foreach($name as $k=>$v) {
echo $city;
echo $region;
etc..
}
The above code does not work. I think I cannot pass a variable from a mySQL loop. The problem is also tat every row I get from the database should be related to the specific $name. So obvioiusly one $name will have its own $city etc..
How do I achieve this?
Please help
You are not retrieving an array with all returned records, you are retrieving an array which contains a single record.
To get the next name (the next record), you must make another call to mysql_fetch_array.
The code you present does that implicitly by assigning $rowGetClaim within a while conditional. A failed mysql_fetch_array call would return false, which would exit the while loop.
There is absolutely no need to use the for each as you presented. Just place the echo right after the assignment (e.g.
$region = $rowGetClaim['region'];
echo $region
Either out put directly fromt eh loop or build an array and then loop through it.
while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
echo $rowGetClaim['Name'];
echo $rowGetClaim['city'];
echo $rowGetClaim['region'];
}
OR
while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
foreach($rowGetClaim as $k => $v{
echo $v;
}
}
OR
$names = array();
while($rowGetClaim = mysql_fetch_array($resultGetClaim)) {
$names[] = $rowGetClaim;
}
foreach($names as $data){
foreach($data as $k => $v) {
echo $v;
}
}

Categories