PHP: foreach loop inside PHP variable? - php

I'm trying to dynamically generate html select options using PHP based on whatever its stored in mysql database.
the column that stores the data called sizez.
the data in that column is stored like so:
small,large,xlarge,xxlarge
so basically the data is separated by a comma.
now in my php page I simply pull the data and display it on my page using a while loop for each product that is stored in the mysql database.
the issue that I am having is that I need to generate a select option dropdown list based on the sizez column for each item.
for that I am using the explode() function and it will generate the select option successfully too.
however, the issue is that it will only get the strings from the first sizez column and ignores the rest of the items But it will display the string from the first column for other items too and it repeats them!
this is my code:
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$sizez = $row["sizez"];
$sizez = preg_replace('/\.$/', '', $sizez); //Remove dot at end if exists
$array = explode(',', $sizez); //split string into array seperated by ','
foreach($array as $value) //loop over values
{
//echo $value . PHP_EOL; //print value
$sizesOption .='<option>'.$value.'</option>';
}
$all_list .="<select>
'.$sizesOption.'
</select>";
so I thought to put the foreach($array as $value) inside the $all_list .= but that approach is wrong.
could someone please advise on this issue?
any help would be appreciated.
EDIT:
The expected result should be like this:
item one item two item three
small large small
large xxlarge xxlarge
However, with my code I get the result like this:
item one item two item three
small small small
large large large
small small
large large
small
large
so basically, it will get the sizes column from the first item and it will repeat it inside select options for other items exactly like the example above.

Since you are generating separate <select> for each iteration, you have to reset $sizeOptions. I suggest using arrays instead of just concatenating strings:
$allList = array();
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$sizesOption = array();
$sizez = preg_replace('/\.$/', '', $row["sizez"]);
$array = explode(',', $sizez);
foreach ($array as $value) {
$sizesOption[] = "<option>{$value}</option>";
}
$all_list[] = '<select>'.implode("\r\n", $sizesOption).'</select>';
}
echo implode("\r\n", $allList);

From what you have posted it looks like you're regenerating $all_list in every iteration of your while loop.
So if you echo $all_list outside of the while loop it will only have the last iteration available - all the other ones having been overwritten during the process of the while loop.

Maybe I am wrong. but as simple as:
$all_list ="<select>".$sizesOption."</select>";

Close the opening braces for while loop before the '$all_list .="' statement.You are iterating the statement inside while loop.
`
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC))
{
$id = $row["id"];
$sizez = $row["sizez"];
$sizez = preg_replace('/\.$/', '', $sizez); //Remove dot at end if exists
$array = explode(',', $sizez); //split string into array seperated by ','
foreach($array as $value) //loop over values
{
//echo $value . PHP_EOL; //print value
$sizesOption .='<option>'.$value.'</option>';
}
}
$all_list .="<select>
'.$sizesOption.'
</select>";
`
May be this will work

I figured it out. Thanks to Justinas's answer. I realized that I had to put my php variable inside the while loop.
so all I had to do was to put $sizesOption =array(); inside my while loop and everything works fine now.
P.S. i haven't made any other changes to my code above.

Related

Foreach returns only first record, stops

This should be very simple, but I'm getting odd behavior I've never seen before. Here is the code:
<?php
$csv = array_map('str_getcsv',file('dummy.csv'));
$n=1;
foreach($csv as $key=>$val) {
$sql = "UPDATE table set field = '$val[$key]' WHERE id = $n";
echo $sql."\n";
$n++;
}
?>
The .csv file is 260 simple text phrases that show up properly with print_r($csv);. The above code gives proper output but stops after the first record. Why?
str_getcsv returns an array.
array_map also returns an array.
So, your $csv is an array with an array within it.
After your line $csv = array_map('str_getcsv',file('dummy.csv'));, add the line $csv = $csv[0]; This pulls out the inner array. Then you should get the expected results without changing the remainder of your code.

How to get each value in a column of database in php

I don't have enough knowledge about this criteria:
I want to loop inside the for each loop to get all values in a particular column.
For example: I got the values from DB through get_result and store the result in $results.
After that use:
for each($results as $result)
❴
$output = $result->message
❵
Where message is a column in DB.
I want to loop over all the messages instead of storing last one by replacing.
Can you please give me suggestions on how to loop inside for each?
Try this:
$output[] = $result ->message;
Now $output will contain all messages on index 0, 1, 2 ...
You are facing the issue because:
$output=$result ->message;
the above line is present inside the loop, and each new iteration onerride the old value.
Well if you just looking for foreach inside foreach then you can try the following.
<?php
foreach($results as $result){
$output=$result->message;
foreach($output as $messages){
echo $messages;
}
}
?>
You don't need to put the message into another variable. You can do whatever you need to do inside the loop. For example, if you are displaying the messages, you can get it done inside the loop:
foreach ($results AS $result) {
echo $results->message . "<br>";
}

Removing Duplicate string from for each loops

I am having an issue removing duplicates from the result of a foreach loop.
The problem more so is the process of how i have the data.
Here is grab the data i need.
$results = mysql_query($query);
while($rows = mysql_fetch_assoc($results)){
extract($rows);
I am trying to grab a column of item_specifiations. Within this column there are multiple data, separated by commas. Some items have more data that others, some are lacking certain data.
$specs = explode("," , $item_specification);
I separate the data using the above method.Then i run the loop to show the data for each item in the DB.
foreach($specs as $spec => $key ){
This now returns every data separated for each item (UPC, PRODUCT_NAME, ETC), which is exactly what i need. But i need only the "BRAND" of the item. So i do the following.
if (strpos($key, 'Brand') === 0) {
$brand = explode(':', $key);
}
Now the problem i am having is certain items having duplicate brand names.
So i want to remove any strings that are returning. The problem is, since this is a loop, there is no way to compare the strings with each other. Each is its own array, so i am dealing with multiple multi-dimensional arrays. I cant figure a way to push them into 1 array then compare, or using something like unique_array.
Any suggestions or help would be appreciated. I have been stuck for awhile.
Use array_unique:
$var = [];
foreach($specs as $spec => $key) {
if(strpos($key,'Brand') === true ) {
$brand[]= implode(',', array_unique(explode(', ',$key)));
}
}
print_r($brand);

Array is reassigning previous values into unset locations, PHP

I am trying to create a multidimensional array at run-time that queries and stores several MySQL results. For instance, let us say we have a table like so (is fictional, so please don't pick at the example):
**store--tag--color--size**
1--101--blue--s
2--102--red--s
2--103--yellow -- m
3--104--blue--m
The need is to create an multi-d array that will store all the products per store. The result I would like is:
$storeArray = array[[[101],[blue],[s]],[[102,103],[red,yellow],[s,m]],[[104],[blue],[m]]];
here is the code I have:
$counter = 0;
foreach($storeIDs as $item){
$result = mysql_query('select whatever');
$rows = mysql_num_rows($result);
for($i=0;$i<$rows;$i++){
$tag[$i] = mysql_result();
$color[$i] = mysql_result();
$size[$i] = mysql_result();
}
$tempArray = array($tag,$,$color,$size);
$storeArray[$counter] = $tempArray;
unset($tempArray);
$counter++;
}
The problem is, even though I have unset $tempArray, the third loop which should capture just
[[104],[blue],[m]]
actually stores
[[104,103],[blue,yellow],[m,m]].
I've tried setting $tempArray to array(), or array(array()). The data from the second loop always spills over into ANY future iteration that is of smaller size.
How can I get $storeArray to look like the goal above?
Thank you
You're unsetting $tmpArray, but it looks like you may need to also unset $tag, $color, and $size as well. There are better approaches with a slightly different data structure, but as is, have you tried this?
unset($tempArray,$tag,$color,$size);
Effectively, you might set $tag[0] and $tag[1] in a loop that has two items. Then, for a loop that has one item you update $tag[0], but $tag[1] remains set.

Count amount of similar items in array, return value if under 3

I have an array which contains sets of three similar named items; however, sometimes there's only two items in a set and I want to call these out.
<?php
$items = array(
'reviewpitfighter-1.138x88.jpg',
'reviewpitfighter-2.138x88.jpg',
'reviewpopfulmailsegacd-1.138x92.jpg',
'reviewpopfulmailsegacd-2.138x76.jpg',
'reviewpopfulmailsegacd-3.138x97.jpg'
);
?>
You'll note that there are two reviewpitfigher* items, and three reviewpopfulmailsegacd* items. I've started down a rabbit hole of loops and feel that there is something simple I'm just glossing over.
May be you can do this as a 2 stage process.
Stage 1:
Loop through the original array and form another set of array with its key as the value of this original array. Then save the repetition count in each of those new arrays.
Stage 2:
Loop through the new set of arrays and then pick out the arrays which has values less than 3 and retrieve its key.
Hope this helps!!
Here's the solution I came up with, sorry it took so long to post.
foreach($images as $value){
$lastItem = explode('-', $images[$count - 1]);
$parts = explode('-', $value);
if(preg_match('/^1/', $parts[1]) && $count != 0){
if(preg_match('/^2/',$lastItem[1])){
$imgurl = preg_replace('/^p?review/','',$lastItem[0]);
$sql = 'SELECT field FROM table WHERE field = "' . $imgurl . '"';
$result = $dbConn->FetchArray($dbConn->Query($sql), MYSQL_ASSOC);
$array[$imgurl] = $result;
}
}
$count++;
}
I get an array of all the images, then I check to see if I'm looking at the first image, if I am then I see if the last image I looked at was the second image. At this point I then call into the database to get some information to display a neatly messaged out put of what reviews are missing a third image. In the end $array contains this list which I can loop over.

Categories