How to compare key and value in more than two array? - php

I am comparing three arrays in nested foreach conditions. Following are the arrays
Array
(
[master/city] => City
[master/national_holiday] => National Holiday
[master/operator_comments] => Operator Comments
[master/sensors] => Sensors
[master/modbus] => Modbus
[master/manufacturers] => Manufacturers
[master/make_model] => Make Model
[master/dispatch_vendors] => Dispatch Vendors
)
Array
(
[1] => View
[2] => Write
)
Array
(
[master/city] => 1
[master/national_holiday] => 2
[master/operator_comments] => 1
[master/sensors] => 2
[master/modbus] => 1
[master/manufacturers] => 2
[master/make_model] => 1
)
Now the scenario is as follows:-
My first foreach iteartes first array
Then in the same foreach i m using second foreach which itrates second array
again in second foreach i m using third foreach to iterate third array
In third foreach , i m comparing key of first array with the key of second array and comparing value of second array with key of third array
If above condition is satisfied then in my dropdown the specific option will append selected Like <option value="1" selected="">View</option>
I am using following code
<?php
$first_array = first_array();
$i = 1;
foreach($first_array as $k => $val) {
?>
<tr>
<td>{{ $i }}</td>
<td class="mailbox-name">{{ $val }}</td>
<td><?php $second_array = second_array(); ?>
<select class="form-control master-menu" name="master_menu[{{$k}}]">
<option value="">Select Role</option>
<?php
foreach ($second_array as $key => $value) {
foreach ($third_array as $mkey => $mval) {
?>
<option value="<?php echo $key; ?>"
<?php if (($mkey == $k) && ($mval == $key)) { echo "selected"; } ?>><?php echo $value; ?></option>
<?php } } ?>
</select>
</td>
</tr>
<?php $i++; } ?>
I am using above code and getting issue that in second array there two values and in third array five values so in my dropdown count of option are ten insted of two.
This is my output.
Please suggest me.

Maybe something like this? I have simplified the process to demonstrate what is happening. I have also added the correct select values:
foreach ($first_array as $key => $value) {
?>
<p><?php echo $value; ?></p>
<?php foreach ($second_array as $second_key => $second_value) { ?>
<?php if ($key == $second_key) { ?>
<select>
<?php foreach ($third_array as $third_key => $third_value) { ?>
<option <?php echo ($third_key == $second_value ? 'selected=selected' : null); ?>><?php echo $third_value; ?></option>
<?php } ?>
</select>
<?php } else { ?>
<select>
<?php foreach ($third_array as $third_key => $third_value) { ?>
<option ><?php echo $third_value; ?></option>
<?php } ?>
</select>
<?php } ?>
<?php } ?>
<?php
}

For example you may try this code
foreach ($tmparray as $innerarray) {
//check type
if (is_array($innerarray)) {
//echo through inner loop
foreach ($innerarray as $value) {
echo $value;
}
} else {
//one,two,three
echo $innerarray;
}
}

Related

get the next key in array in php foreach loop

I have a select box and wanting to get the key of the next value in array to go with the option here is my code
<select>
<?php foreach ($make as $key => $make):?>
<option value="<?php echo next($key);//not correct ?> - <?php echo $key; ?>"> <?php echo $make; ?></option>
<?php endforeach;
Here is the array
Array
(
[0] => Brand
[1] => Alfa Romeo
[123] => Alpina
[142] => Aston Martin
[152] => Audi
[619] => Bentley
[640] => BMW
[1122] => Buick
)
This will work with an associative array as well as numerically indexed:
<?php foreach ($make as $key => $value):?>
<?php next($make); ?>
<option value="<?php echo key($make); ?> - <?php echo $key; ?>"> <?php echo $value; ?></option>
<?php endforeach; ?>
Note, it's confusing and probably a bad idea to use the same variable name for iterating as the array. so instead of foreach ($make as $key => $make) I did foreach ($make as $key => $value) here.
The code above simply advances the pointer on the array and then gets the key for your option value using key(). Since there is no next key on the final array element, the value will be empty.
You can resolve your issue with a lot of solution, but if you have an assoiatve array or none order array or not numirc, you can use this:
<?php
$array = ["a" => 1, "b" => 2, "c" => 3, 1 => "aa"];
next($array);
$key = key($array);
echo $key;
prev($array);
$key = key($array);
echo $key;
Else, if array is ordered and numeric you can use $key + 1;
Simple way to get key of next element is to use array_search of next element of array e.g.
<?php foreach ($makers as $key => $make):?>
<option value="<?php echo array_search( next($makers), $makers );"> <?php echo $make; ?></option>
<?php endforeach;
Hope this helps.
try this function. it finds current key of given value in the array, and from that found key's position, you can get next/previous key with $increment
Ex: when $increment=1, it finds next key
when $increment=2, it finds 2 next key
when $increment=-1, it finds 1 previous key, and so on.
function sov_find_key($findvalue, $array, $increment) {
reset($array);
$key = array_search($findvalue, $array);
if ($key === false || $key === 0){
return false;
}
if ($increment === 0){
return $key;
}
$isNegative = $increment < 0 ? true:false;
$increment = abs($increment);
while(key($array) !== $key) {
next($array);
}
$x=0;
while($x < $increment) {
if( $isNegative ){
prev($array);
} else {
next($array);
}
$x++;
}
return key($array);
}
DEMO: https://3v4l.org/CSSmR
<select>
<?php
foreach ($make as $key => $make):
?>
<option value="<?php echo $key + 1; ?> - <?php echo $key; ?>">
<?php echo $make;
?>
</option>
<?php
endforeach;
Just increment the $key by 1, and you will have the next array element if the keys are in order and are numeric.

Looping the array in select

I have this kind of array shown in Picture. How can i insert the values in the select option as
<option value="7">7</option>
<option value="13000">13000</option>
<option value="19AAAAA">19AAAAA</option>
<option value="sdsdas">sdsdas</option>
<option value="dasdasdasd">dasdasdasd</option>
Simply flatten the multi-dimensional array, and then loop through it.
Suppose $arr in your original multi-dimensional array
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
foreach($it as $value){
?>
<option value="<?php echo $value; ?>"><?php echo $value; ?></option>
<?php
}
Here are the relevant references:
http://php.net/manual/en/class.recursiveiteratoriterator.php
http://php.net/manual/en/class.recursivearrayiterator.php
<?php
foreach($arr as $val){
foreach($val as $val2){
foreach($val2 as $val3){ ?>
<option value="<?php echo $val3;?>"><?php echo $val3 ;?></option><?php
}
}
}
?>
You need to flat array. You can do it with recursive function. Here you have general function for that.
/**
* Get multilevel array convert to single-level array
* #param $array
* #return array
*/
function getFlattened($array) {
$flattened = [];
foreach ($array as $flat) {
if (is_array($flat)) {
$flatArray = array_merge($flatArray, getFlattened($flat));
} else {
$flattened[] = $flat;
}
}
return $flattened;
}
Of course you can use that approach to recursively display select - not only to flat array.
<?php foreach($array as $inner): ?>
<?php foreach($inner as $innerTwo): ?>
<?php foreach($innerTwo as $item): ?>
<option value="<?= $item ?>"><?= $item ?></option>
<?php endforeach; ?>
<?php endforeach; ?>
<?php endforeach; ?>
you may try this.
<?php
$input = Array(
Array
(
0 => 7,
1 => 13000
),
Array
(
0 => '19AAAAA',
1 => 'sdsdas'
)
);
$options = "";
$result = call_user_func_array("array_merge", $input);
for($i = 0;$i< count($result);$i++ ){
$options .="<option value='".$result[$i]."'>".$result[$i]."</option>";
}
echo $options;

Set select box value from array

I have this UI:
Also, I have this PHP Back-end code:
<select name="as<?php echo $product['product_id']; ?>[]" style="width:250px;">
<?php
foreach ($product['uniSku'] as $key => $value) {
echo '<option value="'.$key.'">'.$value.'</option>';
}
?>
</select>
The question is, how can i put the data SKU from array into the select box?
You need to iterate twice in your multidimesional array
foreach ($product['uniSku'] as $data) {
foreach($data as $key => $val) {
echo '<option value="'.$key.'">'.$val.'</option>';
}
}
Or if you need to use keys from your parent array you can store it in a variable at first iteration
foreach ($product['uniSku'] as $kk => $data) {
foreach($data as $key => $val) {
echo '<option value="'.$kk.'">'.$val.'</option>';
}
}
Try this
Replace values with $value['sku']
foreach ($product['uniSku'] as $key => $value) {
echo '<option value="'.$key.'">'.$value['sku'].'</option>';
}
Here the solution
foreach ($product['uniSku'] as $key => $value) {
echo '<option value="'.$key.'">'.$value['sku'].'</option>';
}

Generate "select inputs" through loops in arrays

I have the following array:
$selects = array(
'Select1' => array('select1_name' => array('select1_value1','select1_value1')),
'Select2' => array('select2_name' => array('select2_value1','select2_value2'))
);
I wonder how I can generate these "selects inputs" with their options through a loop?
You need one cycle, which will loop through selects array and inside this cycle, you need another one, which will loop through selects. And inside this one, you need one more, which will loop through the option values:
$selects = array(
'Select1' => array('select1_name' => array('select1_value1','select1_value1')),
'Select2' => array('select2_name' => array('select2_value1','select2_value2'))
);
foreach($selects as $select) {
foreach($select as $item) {
echo "<select>";
foreach($item as $value) {
echo "<option value=".$value.">".$value."</option>";
}
echo "</select>";
}
}
This will produce:
<select>
<option value=select1_value1>select1_value1</option>
<option value=select1_value1>select1_value1</option>
</select>
<select>
<option value=select2_value1>select2_value1</option>
<option value=select2_value2>select2_value2</option>
</select>
foreach($selects as $select) {
foreach($select as $selectName => $value) {
echo '<select> ';
echo '<option>'.$selectName.'</option>';
foreach($value as $v) {
echo '<option>'.$v.'</option>';
}
echo '</select>';
}
}
echo '<select> ';
foreach($selects as $array) {
foreach($array as $value) {
foreach($value as $v) {
echo '<option value="'.$v.'">'.$v.'</option>';
}}}
echo '</select>';

Foreach giving erroneous $value

This has me stumped. print_r displays the correct array indices and values, but the foreach construct retrieves erroneous values and even changes the value for the last index even though I'm not retrieving the values by reference (not using the ampersand).
<?php
require './includes/dbal.php';
require './includes/user.php';
require './includes/book.php';
session_start();
$title='My Shopping Cart';
include './template/header.php';
if(!isset($_SESSION['user']))
{
die('You are not logged in.');
}
if(!isset($_SESSION['cart']))
{
$_SESSION['cart'] = array();
}
if(isset($_POST['submit']) && strcmp($_GET['mode'], 'add') == 0)
{
if(filter_var($_POST['qty'], FILTER_VALIDATE_INT) == FALSE)
{
echo '<div style="color: red;">Invalid quantity specified. Please go back and use a valid quantity.</div>';
}
else
{
$_SESSION['cart'][$_POST['book_id']] = $_POST['qty'];
}
}
else if(isset($_POST['update']) && strcmp($_GET['mode'], 'update') == 0)
{
foreach($_SESSION['cart'] as $key => &$value)
{
if((int) $_POST["qty_$key"] === 0)
{
unset($_SESSION['cart']["$key"]);
}
else
{
$value = $_POST["qty_$key"];
}
}
}
echo '<h3>Your shopping cart</h3>';
$db = new DBal();
$total=0;
echo '<div id="cart-items"><ul><form action="./cart.php?mode=update" method="post">';
// echo 'Original array: '; print_r($_SESSION['cart']);
foreach($_SESSION['cart'] as $key => $value)
{
// echo '<br />$key => $value for this iteration: ' . "$key => $value<br />";
// print_r($_SESSION['cart']);
$b = new Book($key, $db);
$book = $b->get_book_details();
$total += $value * $book['book_nprice']
?>
<li>
<div><img src="./images/books/thumbs/book-<?php echo $book['book_id']; ?>.jpg" title="<?php echo $book['book_name']; ?>" /></div>
<span class="cart-price">Amount: Rs. <?php echo $value * $book['book_nprice']; ?></span>
<h3><?php echo $book['book_name']; ?> by <?php echo $book['book_author']; ?></h3>
Price: Rs. <?php echo $book['book_nprice']; ?><br /><br />
Qty: <input type="number" name="qty_<?php echo $book['book_id']; ?>" maxlength="3" size="6" min="1" max="100" value="<?php echo $value; ?>" /><br />
</li>
<?php } echo "<span class=\"cart-price\">Total amount: $total</span>" ?>
<br />
<input type="submit" name="update" value="Update Cart" />
</form></ul></div>
<?php include './template/footer.html'; ?>
Sample output after pressing the update button is like this :
Original array:
Array (
[9] => 6
[8] => 7
[3] => 8
)
$key => $value for this iteration: 9 => 6
Array (
[9] => 6
[8] => 7
[3] => 6
)
$key => $value for this iteration: 8 => 7
Array (
[9] => 6
[8] => 7
[3] => 7
)
$key => $value for this iteration: 3 => 7
Array (
[9] => 6
[8] => 7
[3] => 7
)
The value for the last index gets changes to the value of the current index in every iteration. This results in the last value output having the same value as the second-to-last index.
Help?
You were using &$value as reference before:
foreach($_SESSION['cart'] as $key => &$value)
The variable continues to exist as reference beyond the loop, using it again in a loop has expected but non-obvious side effects. This is even mentioned in a big red box in the manual. unset($value) after the first loop to avoid that.
You are using references here:
foreach($_SESSION['cart'] as $key => &$value)
Either don't use reference here or unset $value immediately after the loop.

Categories