2 for loops nested and selected inside one based on outer - php

I have these arrays:
$payments = array(1=>'Cash',2=>Cheque,3=>credit,4=>other);
$selected = array(2,1);
foreach($payments as $key=>$value) {
foreach($selected as $id) {
if ($key == $id) {
echo $id . "is selected" . '<br>';
}
else{
echo $id . " is not selected" . '<br>';
}
}
}
what expected:
1 is selected
2 is not selected
3 is not selected
4 is selected
but i got:
1 is not selected
1 is selected
2 is selected
2 is not selected
3 is not selected
3 is not selected
4 is not selected
4 is not selected
what's the wrong in my loops?

You don't need inner loop:
$payments = array(1=>'Cash',2=>Cheque,3=>credit,4=>other);
$selected = array(2,1);
foreach($payments as $key=>$value) {
if (in_array($key, $selected)( {
echo $key . "is selected" . '<br>';
} else {
echo $key . " is not selected" . '<br>';
}
}

You could simply use in_array() to check if an element is selected:
$payments = array(1=>'Cash',2=>'Cheque',3=>'credit',4=>'other');
$selected = array(2,1);
foreach($payments as $key=>$value) {
if (in_array($key, $selected)) {
echo $value . "is selected" . '<br>';
} else {
echo $value . " is not selected" . '<br>';
}
}
By the way, you need quotes around the payment method names.

You can use in_array() instead, so you can omit your inner loop:
foreach($payments as $key=>$value) {
if (in_array($key, $selected)) {
echo $id . "is selected" . '<br>';
}else{
echo $id . " is not selected" . '<br>';
}
}
Example

UPDATE: an alternative solution. Not better (maybe), but different :)
$payments = array(1=>'Cash', 2=>'Cheque', 3=>'Credit', 4=>'Other');
$selected = array('Cash','Cheque');
foreach($selected as $chosen){
$selected_values = array_search($chosen, $payments);
echo "Number ". $selected_values." (".$chosen.") is selected.<br>";
}
You can see the output here
Old solution (as everyone else...)
$payments = array(1=>'Cash', 2=>'Cheque',3=>'Credit',4=>'Other');
$selected = array(2,1);
foreach($payments as $key=>$value) {
if (in_array($key, $selected)) {
echo $key. " is selected" . '<br>';
}else{
echo $key. " is not selected" . '<br>';
}
}

Related

Iterate through Nested array in PHP

I have a nested array on this link Array Sample
I am using code below to parse this, but second and beyond depth it's returning nothing. However tried with recursive function.
printAllValues($ArrXML);
function printAllValues($arr) {
$keys = array_keys($arr);
for($i = 0; $i < count($arr); $i++) {
echo $keys[$i] . "$i.{<br>";
foreach($arr[$keys[$i]] as $key => $value) {
if(is_array($value))
{
printAllValues($value);
}
else
{
echo $key . " : " . $value . "<br>";
}
}
echo "}<br>";
}
}
What I am doing Wrong? Please help.
Version of J. Litvak's answer that works with SimpleXMLElement objects.
function show($array) {
foreach ($array as $key => $value) {
if (!empty($value->children())) {
show($value);
} else {
echo 'key=' . $key . ' value=' . $value. "<br>";
}
}
}
show($ArrXML);
You can use recurcive function to print all values:
function show($array) {
foreach( $array as $key => $value) {
if (is_array($value)) {
show($value);
} else{
echo 'key=' . $key . ' value=' . $value. "<br>";
}
}
}
show($ArrXML);

PHP Bootstrap multi select options

In my code I am using PHP which populates the bootstrap multi selectpicker from MySQL database but the problem is it only selects the last option instead of multiple options, I don't know what I am missing in it? Here is my my code
function MultiBindCombo($tablenames, $columnnames1, $columnnames2, $comboname, $selectedopt) {
global $conn;
$sql="SELECT ". $columnnames1. ", " . $columnnames2 . " FROM ". $tablenames;
$result = mysqli_query($conn, $sql);
if( ! $result ) {
echo mysql_error();
exit;
}
echo '<select class="selectpicker form-control" data-live-search="true" name="' . $comboname . '" multiple="multiple">';
$array = explode(',', $selectedopt);
while ($row=mysqli_fetch_array($result)) {
foreach ($array as $select_option){
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
} else {
$print_selected = '';
}
echo $select_option;
}
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}
echo '</select>';
}
To get all selected values in a multiselect you need to use name attribute with []:
echo '<select class="selectpicker form-control" data-live-search="true" name="' . $comboname . '[]" multiple="multiple">';
After that you can iterate over $_POST[$comboname] with a foreach.
Update:
Let's look closer to your code here:
while ($row=mysqli_fetch_array($result)) {
foreach ($array as $select_option){
// You iterate over every value of array, so in the end
// `$print_selected` is defined depending on value of the
// last `$select_option`
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
} else {
$print_selected = '';
}
// remove this. Why you echo `$select_option`?
echo $select_option;
}
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}
Rewrite it as:
while ($row=mysqli_fetch_array($result)) {
$print_selected = '';
foreach ($array as $select_option){
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
// break `foreach` as you found the right item
break;
}
}
// if right item is not found - `$print_selected` is empty
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}

Magento Get Products By Manufacturer

I have the following code which gets me a list of manufacturers:
$attribute = Mage::getModel('eav/entity_attribute')
->loadByCode('catalog_product', 'manufacturer');
$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attribute->getData('attribute_id'))
->setStoreFilter(0, false);
$preparedManufacturers = array();
foreach($valuesCollection as $value) {
$preparedManufacturers[$value->getOptionId()] = $value->getValue();
}
if (count($preparedManufacturers)) {
echo "<h2>Manufacturers</h2><ul>";
foreach($preparedManufacturers as $optionId => $value) {
echo "<li>" . $value . " - (ID:" . $optionId . ")</li>";
}
echo "</ul>";
}
How do I get the first product of each manufacturer?
Thanks
try this
if (count($preparedManufacturers)) {
echo "<h2>Manufacturers</h2><ul>";
foreach($preparedManufacturers as $optionId => $value) {
<!-- add the this code for get first item id -->
$firstProductId=Mage::getModel('catalog/product')->getCollection()
->addStoreFilter(0)
->addAttributeToFilter('manufacturer',$optionId)->getFirstItem()->getId();
echo "<li>" . $value . " - (ID:" . $optionId . ")</li>";
}
echo "</ul>";
}

Can i nest a foreach within foreach?

I have an array: $categories = array("item1", "item2", "item3");
I also have three arrays: $item1Array = array("hi", "items");, $item2Array = array("hi", "items");, $item3Array = array("hi", "items");
I stated a foreach like this:
foreach ($categories as &$value) {
echo "<optgroup label='" . $value . "'>';
$nextArray = $value . "Array";
foreach($nextArray as &$nextValue) {
echo "<option value='" . $nextValue . "'>" . $nextValue . "</option>";
}
}
but it get an error Warning: invalid argument supplied for foreach().
Is there a way I can achieve this?
Yes, you could, by ${$nextArray}. but notice named variables is not good practice, you could use associative array instead.
And note you don't need to use reference in this case.
$categories = array("item1", "item2", "item3");
$item1Array = array("hi", "items");
$item2Array = array("hi", "items");
$item3Array = array("hi", "items");
foreach ($categories as $value) {
echo "<optgroup label='" . $value . "'>";
$nextArray = $value . "Array";
foreach(${$nextArray} as $nextValue) {
echo "<option value='" . $nextValue . "'>" . $nextValue . "</option>";
}
}
Of course, but as you can clearly see from the syntax highlighting of your post, you used a ' instead of a " at the end of the "optgroup" line.
Also, you could just use a nested array:
$categories = Array(
"item1"=>Array("hi","items"),
"item2"=>Array("hi","items"),
"item3"=>Array("hi","items"),
);
foreach($categories as $key=>$array) {
echo "<optgroup label='".$key."'>";
foreach($array as $value) {
echo "<option>".$value."</option>";
}
echo "</optgroup>";
}

Displaying column names and values

I want to display the column names along with the values in the PHP page.
while($get_info = mysql_fetch_row($orderdetails))
{
foreach ($get_info as $field)
{
echo "<td>" . $field . "</td>";
}
echo '</tr>';
}
This fetches just the values. How do I display the column names too?
The column names are order_id, productid, product_discount, amount, customerid, order_date.
while($get_info=mysql_fetch_array($orderdetails))
{
foreach ($get_info as $key => $val)
{
echo "<td>" .$key. ': ' . $val . "</td>";
}
echo '</tr>';
}
You are just missing the key from your foreach :
while($get_info=mysql_fetch_assoc($orderdetails))
{
foreach ($get_info as $field => $value)
{
echo "<td>" .$field.': '.$value."</td>";
}
echo '</tr>';
}
You might want to review your foreach php documentation for more information:
http://php.net/manual/en/control-structures.foreach.php
If you want each field to contain the column name, change it to mysql_fetch_array and do:
foreach($get_info as $key => $value) {
echo "<td>$key: $value</td>";
}
If you want the column names to be at the top of the table, you can either check the first row (if you're sure the table won't be empty):
$first = true;
while($get_info = mysql_fetch_assoc($orderdetails)) {
echo '<tr>';
if($first) {
$first = false;
foreach(array_keys($get_info) as $columnName) {
echo '<th>' . $columnName . '</th>';
}
echo '</tr><tr>';
}
foreach($get_info as $field) {
echo '<td>' . $field . '</td>';
}
echo '</tr>';
}
If you're not sure that the table will have at least one element, I would use a second DESCRIBE query.
while ($get_info=mysql_fetch_assoc($orderdetails))
{
foreach ($get_info as $columnName => $field)
{
echo "<td>$columnName: $field</td>";
}
echo '</tr>';
}
Notice that I am using mysql_fetch_assoc() which fetches the row having the column names as the keys.
<?php
while($get_info=mysql_fetch_array($orderdetails))
{
foreach ($get_info as $key => $val)
{
echo "column is " .$key. 'and value is ' . $val ;
}
echo '</br>';
}
?>
A lot of people are using a key => val demo but your code will work its just that your $field is now an a key so you need to tell it what column to look at.
When echoing just go
echo "<td>" . $field->column . "</td>";
That should work.

Categories