php second foreach doesn't write out values - php

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>";
}

Related

PHP Add New Line to Array Values Inside One Row and Column in Database Table

I managed to add multiple data in one column in the database, but now I need to display it with a new line in the browser so they don't stick with each other as I display them as an array in one column.
Here is my code:
if (isset($_GET['id']) && $_GET['id'] == 5) {
$subArray = array("StudentAnswer");
$subId6 = $db->get("answertable", null, $subArray);
foreach ($subId6 as $sub) {
$answers[] = $sub['StudentAnswer'] . "\n";
}
foreach ($answers as $row) {
$answers2 = explode("||", $row[0]);
foreach($answers2 as $row2){
$answers3 = $row2 . '\n';
}
}
$db->where('AccessId', $_GET['token']);
$db->where('StudentAnswer', $answers3);
$subId8 = $db->get("answertable");
if ($subId8) {
echo json_encode($subId8);
}
}
You are overriding $subId6 after getting its content. Try to fetch the table $rows in a new variable and the extract the content from it, like the code below.
<?php
// Example of $subId6 content
$subId6 = array(["StudentAnswer" => ["Answer 1\nAnswer 2\nAnswer 3"]], ["StudentAnswer" => ["Answer 1\nAnswer 2\nAnswer 3"]]);
// Fetch rows
foreach ($subId6 as $sub) {
$rows[] = $sub['StudentAnswer'];
}
// Decode rows
foreach($rows as $row) {
$answers = explode("\n", $row[0]);
echo "New answers: \n";
// Split answers in single answer
foreach ($answers as $answer)
echo "$answer \n";
echo "\n";
}
You will have a list of all the answers split for table rows
If you want a string of answers seperated by a space then simply do
if (isset($_GET['id']) && $_GET['id'] == 5) {
$subId6 = $db->get("answertable");
foreach ($subId6 as $sub) {
$answers .= $sub['StudentAnswer'] . ' ';
}
$answers= rtrim($answers, ' '); //remove last space in case thats an issue later
$db->where('AccessId', $_GET['token']);
$db->where('StudentAnswer', $answers);
$subId8 = $db->get("answertable");
if ($subId8) {
echo json_encode($subId8);
}
}

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'];
}
}

How to use variables within a PHP array

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.

Echo values of arrays?

I want to echo the values of all arrays that has been returned from a search function. Each array contains one $category, that have been gathered from my DB. The code that I've written so far to echo these as their original value (e.g. in the same form they lay in my DB.) is:
$rows = search($rows);
if (count($rows) > 0) {
foreach($rows as $row => $texts) {
foreach ($texts as $idea) {
echo $idea;
}
}
}
However, the only thing this code echoes is a long string of all the info that exists in my DB.
The function, which result I'm calling looks like this:
function search($query) {
$query = mysql_real_escape_string(preg_replace("[^A-Za-zÅÄÖåäö0-9 -_.]", "", $query));
$sql = "SELECT * FROM `text` WHERE categories LIKE '%$query%'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows['text'] = $row;
}
mysql_free_result($result);
return $rows;
}
How can I make it echo the actual text that should be the value of the array?
This line: echo $rows['categories'] = $row; in your search function is problematic. For every pass in your while loop, you are storing all rows with the same key. The effect is only successfully storing the last row from your returned query.
You should change this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
echo $rows['categories'] = $row;
}
mysql_free_result($result);
return $rows;
to this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
Then when you are accessing the returned value, you could handle it like the following...
foreach ($rows as $key => $array) {
echo $array['columnName'];
// or
foreach ($array as $column => $value) {
echo $column; // column name
echo $value; // stored value
}
}
The problem is that you have a multi-dimensional array, that is each element of your array is another array.
Instead of
echo $row['categories'];
try print_r:
print_r($row['categories']);
This will technically do what you ask, but more importantly, it will help you understand the structure of your sub-arrays, so you can print the specific indices you want instead of dumping the entire array to the screen.
What does a var_dump($rows) look like? Sounds like it's a multidimensional array. You may need to have two (or more) loops:
foreach($rows as $row => $categories) {
foreach($categories as $category) {
echo $category;
}
}
I think this should work:
foreach ($rows as $row => $categories) {
echo $categories;
}
If this will output a sequence of Array's again, try to see what in it:
foreach ($rows as $row => $categories) {
print_r($categories);
}

Displaying an associative array in PHP

I am trying to build a function that extracts information from a database and inserts it into an associative array in PHP using mysql_fetch_assoc, and return the array so another function can display it. I need a way to display the returned assoc array. This should be a different function from the first one
print_r($array) will give nicely formatted (textually, not html) output.
If you just want information about what is in the array (for debugging purposes), you can use print_r($array) or var_dump($array), or var_export($array) to print it in PHP's array format.
If you want nicely formatted output, you might want to do something like:
<table border="1">
<?php
foreach($array as $name => $value) {
echo "<tr><th>".htmlspecialchars($name).
"</th><td>".htmlspecialchars($value)."</th></tr>";
}
?>
</table>
This will, as you might already see, print a nicely formatted table with the names in the left column and the values in the right column.
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $column => $value) {
//Column name is in $column, value in $value
//do displaying here
}
}
If this is a new program, consider using the mysqli extension instead.
Assuming you've made the call, and got $result back:
$array = new array();
while($row = mysql_fetch_assoc($result)){
$array[] = $row;
}
return $array;
This should get you going:
$rows = mysql_query("select * from whatever");
if ($rows) {
while ($record = mysql_fetch_array($rows)) {
echo $record["column1"];
echo $record["column2"];
// or you could just var_dump($record); to see what came back...
}
}
The following should work:
$rows = mysql_query("select * from whatever");
if ($rows) {
$header = true;
while ($record = mysql_fetch_assoc($rows)) {
if ($header) {
echo '<tr>';
foreach (array_keys($record) AS $col) {
echo '<td>'.htmlspecialchars($col).'</td>';
}
echo '</tr>';
$header = false;
}
echo '<tr>';
foreach (array_values($record) AS $col) {
echo '<td>'.htmlspecialchars($col).'</td>';
}
echo '</tr>';
}
}
(Yes, blatant mod of Fosco's code)
This should print the column headers once, then the contents after that. This would print just whatever columns were retrieved from the DB, regardless of the query.

Categories