PHP Optgroup in Foreach - php

i'm on making payment system dropdown system, and have issue, with optgroup for mobile payments. This is example, of response from MySQL.
[17]=>
array(5) {
["id"]=>
string(2) "34"
["region"]=>
string(1) "1"
["type"]=>
string(2) "18"
["mobile"]=>
string(1) "0"
["system"]=>
string(1) "1"
}
[18]=>
array(5) {
["id"]=>
string(2) "35"
["region"]=>
string(1) "1"
["type"]=>
string(2) "19"
["mobile"]=>
string(1) "0"
["system"]=>
string(1) "1"
}
[19]=>
array(5) {
["id"]=>
string(2) "36"
["region"]=>
string(1) "1"
["type"]=>
string(2) "20"
["mobile"]=>
string(1) "1"
["system"]=>
string(1) "1"
}
[20]=>
array(5) {
["id"]=>
string(2) "37"
["region"]=>
string(1) "1"
["type"]=>
string(2) "20"
["mobile"]=>
string(1) "2"
["system"]=>
string(1) "1"
}
[21]=>
array(5) {
["id"]=>
string(2) "38"
["region"]=>
string(1) "1"
["type"]=>
string(2) "20"
["mobile"]=>
string(1) "3"
["system"]=>
string(1) "1"
}
So where ['type'] === 20 && ['mobile'] != 0 i need for making optgroup with label mobile payments..
if ( ! empty ( $regions ) && $regions !== NULL ) {
$array = array();
$im = 0;
$i = 0;
var_dump( $regions );
foreach ( $regions as $key => $region ) {
if ( (int) $region['mobile'] === 0 ) {
$type = $db->getTypeById( (int) $region['type'] );
$value = $region['type'];
echo "<option value='{$value}'>{$type}</option>";
} else {
//if ( $i < 1 )
//echo '<optgroup label="Mobile payments">';
$type = $db->getMobileById( (int) $region['mobile'] );
$value = $region['type'] . '_' . $region['mobile'];
echo "<option value='{$value}'>{$type}</option>";
//if ( $i <= $im )
//echo '</optgroup>';
$i++;
}
}
}
My dropdown
So my problem is to make proper group without repeating it on every mobile payments in each region (continent)
Should be soemthing like this: https://jsfiddle.net/atc67mLe/24/
Thank you.

If you don't need the optgroup in the middle of your options, you could just add it at the end.
if (!empty($regions)) {
$mobileOptions = [];
// Print normal options
foreach ($regions as $region) {
$typeId = $region['type'];
if ($typeId == 20 && $region['mobile'] != 0) {
$mobileOptions[] = $region;
} else {
$label = $db->getTypeById($typeId);
echo "<option value='{$typeId}'>{$label}</option>";
}
}
// Print mobile options
if (!empty($mobileOptions)) {
echo '<optgroup label="Mobile payments">';
foreach ($mobileOptions as $region) {
$mobileId = $region['mobile'];
$typeId = $region['type'];
$label = $db->getMobileById($mobileId);
echo "<option value=\"{$typeId}_{$mobileId}\">{$label}</option>";
}
echo '</optgroup>';
}
}
This is untested, but you get the idea. Just separate the mobile ones into a new array and loop through them to make the optgroup afterwards.
I would probably try to refine the initial SQL query though, to retrieve a more usable set of results rather than running a bunch of extra queries in the loop for every option. It would be better to have a join in your first SQL query, to get the payment method name at the same time.

the issue in your code is you wrapping each mobile payment option with optgroup. What you have to do is to group all mobile payment options in array or in a string and then wrapping them all with optgroup before print them out
here is an example ...
$options = '';
$mobileOptions = '';
foreach ($regions as $region) {
$typeId = $region['type'];
if ($typeId == 20 && $region['mobile'] != 0) {
$label = $db->getMobileById($region['mobile']);
$mobileOptions .= sprintf('<option value="%s_%s">%s</option>',$typeId,$region['mobile'],$label);
} else {
$label = $db->getTypeById($typeId);
$options .= sprintf('<option value="%s">%s</option>',$typeId,$label);
}
}
echo $options;
if ($mobileOptions)
echo '<optgroup label="Mobile payments">'.$mobileOptions.'</optgroup>';

Related

ECHO of an object breaking page

I have the following code that when used breaks my page. What am I not doing correctly?
$check_availability = $wpdb->get_results($wpdb->prepare("SELECT id FROM mytablename "));
foreach ($check_availability as $available){
echo $available . "<br>\n";
}
Ive tried moving the echo out of the loop. Same broken page result. This worked correctly when I had NO foreach loop at all but then it would only return 1 result instead of many.
EDIT 1 to show var_dump($available) result inside the loop -
object(stdClass)#2314 (1) { ["id"]=> string(1) "4" } object(stdClass)#2361 (1) { ["id"]=> string(1) "6" }
If I var_dump($check_availability ) outside of the loop then I get
array(2) { [0]=> object(stdClass)#2314 (1) { ["id"]=> string(1) "4" } [1]=> object(stdClass)#2361 (1) { ["id"]=> string(1) "6" } } array(2) { [0]=> object(stdClass)#2314 (1) { ["id"]=> string(1) "4" } [1]=> object(stdClass)#2361 (1) { ["id"]=> string(1) "6" } }
The "echo" function can only print strings / numbers.
In this case you are trying to print an object.
If you want to print the id try writing:
$check_availability = $wpdb->get_results($wpdb->prepare("SELECT id FROM mytablename "));
foreach ($check_availability as $available){
echo $available->id . "<br>\n";
}
If you are interested in knowing what '$available' contains, run this:
$check_availability = $wpdb->get_results($wpdb->prepare("SELECT id FROM mytablename "));
foreach ($check_availability as $available){
var_dump($available);
}

How to fetch arrays with string in php

how can i fetch data in an arrays with gives null value if null
here is my data I var_dump($showStatus); I want to print out . $showStatus[0]['title']
string(0) ""
array(2) {
[0]=>
array(7) {
["id"]=>
string(1) "1"
["container_id"]=>
string(1) "3"
["title"]=>
string(51) "waitting"
}
[1]=>
array(7) {
["id"]=>
string(1) "2"
["container_id"]=>
string(1) "3"
["title"]=>
string(72) "getting"
}
}
array(1) {
[0]=>
array(7) {
["id"]=>
string(1) "4"
["container_id"]=>
string(1) "7"
["title"]=>
string(51) "getting"
}
}
The reason that I've string because in my models I want to print "" or NULL when it don't have data here is my models
public function showStatus($id){
$sql = 'SELECT * FROM status WHERE container_id = '.$id;
if($this->query_rows( $sql )) {
return $this->query_rows($sql);
} else {
return "";
}
}
I try to use
foreach ($getListData as $k) {
}
but it said Warning: Invalid argument supplied for foreach()
Try this:
if(!empty($getListData) )
{
foreach ($getListData as $k) {
print_r($k);
}
}
else {
echo "NULL";
}

PHP: Combining data with a shared key from a single array into new array

I have this array:
array(5) {
[0]=>
array(4) {
["productCode"]=>
string(4) "X001"
["productUPC"]=>
string(3) "261"
["productTextSeq"]=>
string(1) "1"
["productTxtVal"]=>
string(5) "Text1"
}
[1]=>
array(4) {
["productCode"]=>
string(4) "X001"
["productUPC"]=>
string(3) "261"
["productTextSeq"]=>
string(1) "2"
["productTxtVal"]=>
string(5) "Text2"
}
[2]=>
array(4) {
["productCode"]=>
string(4) "X001"
["productUPC"]=>
string(3) "261"
["productTextSeq"]=>
string(1) "3"
["productTxtVal"]=>
string(5) "Text3"
}
[3]=>
array(4) {
["productCode"]=>
string(4) "X002"
["productUPC"]=>
string(3) "262"
["productTextSeq"]=>
string(1) "1"
["productTxtVal"]=>
string(5) "Text1"
}
[4]=>
array(4) {
["productCode"]=>
string(4) "X002"
["productUPC"]=>
string(3) "262"
["productTextSeq"]=>
string(1) "2"
["productTxtVal"]=>
string(5) "Text2"
}
}
With the above input, I want the output array to look like this:
array(2) {
[0]=>
array(3) {
["productCode"]=>
string(4) "X001"
["productUPC"]=>
string(3) "261"
["productTxtVal"]=>
string(17) "Text1 Text2 Text3"
}
[1]=>
array(3) {
["productCode"]=>
string(4) "X002"
["productUPC"]=>
string(3) "262"
["productTxtVal"]=>
string(11) "Text1 Text2"
}
}
The resulting array does not need the productTextSeq key, just the combined values of productTextVal, when the productCode is the same. I've searched SO for examples of this but it seems every example I've found are based on multiple input arrays. I know I can brute force this with nested foreach functions but would love a more elegant solution.
I ended up just doing it the brute force method, here is my solution if anyone's interested:
$productData = array();
$sortedData = array();
$comments = '';
$saveKey = '';
$appendComment = false;
$idx = 0;
foreach ($data as $key=>$value) {
foreach ($value as $k=>$v) {
if ($k == 'productCode') {
if ($v == $saveKey) {
$appendComment = true;
} else {
$appendComment = false;
$saveKey = $v;
if ($idx !== 0) { // Don't write to array on first iteration!
$productData['productTxtVal'] = $comments;
$sortedData[] = $productData;
}
}
}
if ($k == 'productTxtVal') {
if ($appendComment == true) {
$comments .= ' ' . trim($v);
} else {
$comments = trim($v);
}
}
}
$productData = $value;
$idx++;
}
Not "elegant" but it works. I also have a check after this logic in case only one productCode is in the original array, as it won't be written to the $sortedData array since the key never changes.
The following code assumes you control the contents of the original data array (due to risk of injection using extract() function) and that no 2 items with the same productCode have the same productTextSeq.
$products = [];
foreach ($data as $item) {
// extract contents of item array into variables
extract($item);
if (!isset($products[$productCode])) {
// create product array with code, upc, text as array
$products[$productCode] = compact('productCode', 'productUPC') + ['productTxtVal' => []];
}
// add text value to array with sequence as index
$products[$productCode]['productTxtVal'][$productTextSeq] = $productTxtVal;
}
$products = array_values( // ignore array keys
array_map(function($product) {
ksort($product['productTxtVal']); // sort text as array by index/ sequence
$product['productTxtVal'] = implode(' ', $product['productTxtVal']); // implode into string
return $product;
}, $products)
);
You can run the code here: https://repl.it/BWQL

$_POST values changing or disappearing inside foreach loop

Prior to this foreach loop $_POST['encounterName'] contains a predefined name. Inside the loop its value changes to ".json" so the first string in file_put_contents reads ".json.json". As well $_POST['basicTrainingSectionSlide'], $_POST['basicTrainingContentHeader'], and
$_POST['basicTrainingContentText'] lose their values. After the foreach loop, all values go back to normal. What is happening here?
$i = 0;
$j = 0;
foreach($_POST['Sections'] as $order){
if(strcmp($order, "Section") == 0){
file_put_contents($_POST['encounterName'].".json", "\t\t[\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t\t\"Section\",\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t\t\"".$_POST['basicTrainingSectionSlide'][$i]."\"\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t],\n", FILE_APPEND);
$i++;
}
else if(strcmp($order, "Text") == 0){
file_put_contents($_POST['encounterName'].".json", "\t\t[\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t\t\"Text\",\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t\t\"".$_POST['basicTrainingContentHeader'][$j]."\"\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t\t\"".$_POST['basicTrainingContentText'][$j]."\"\n", FILE_APPEND);
file_put_contents($_POST['encounterName'].".json", "\t\t],\n", FILE_APPEND);
$j++;
}
}
This is what the $_post array contains:
array(11) { ["encounterName"]=> string(8) "Violence" ["encounterHint"]=> string(0) "" ["basicTrainingSectionSlide"]=> array(2) { [0]=> string(1) "1" [1]=> string(1) "6" } ["basicTrainingContentHeader"]=> array(2) { [0]=> string(1) "2" [1]=> string(1) "4" } ["basicTrainingContentText"]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "5" } ["contextText_1"]=> string(0) "" ["contextText_2"]=> string(0) "" ["contextText_3"]=> string(0) "" ["contextText_4"]=> string(0) "" ["contextText_5"]=> string(0) "" ["submit_form"]=> string(6) "Submit" } array(11) { ["encounterName"]=> string(8) "Violence" ["encounterHint"]=> string(0) "" ["basicTrainingSectionSlide"]=> array(2) { [0]=> string(1) "1" [1]=> string(1) "6" } ["basicTrainingContentHeader"]=> array(2) { [0]=> string(1) "2" [1]=> string(1) "4" } ["basicTrainingContentText"]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "5" } ["submit_form"]=> string(6) "Submit" }
Some added information:
-The form that is filled out sends its post data to a separate php file for processing.
-The $_POST['Sections'] is sent via this function:
function returnValues() {
$.ajax({
type: "POST",
url: "final.php",
data:{ Sections: $sectionOrder },
success: function(data){
console.log(data);
}
})
}
from a .js file onsubmit of the form tag.
Assuming that $_POST['Sections'] contains something like:
array(11) {
["encounterName"]=> string(8) "Violence"
["encounterHint"]=> string(0) ""
["basicTrainingSectionSlide"]=> array(2) {
[0]=> string(1) "1"
[1]=> string(1) "6" }
["basicTrainingContentHeader"]=> array(2) {
[0]=> string(1) "2"
[1]=> string(1) "4" }
["basicTrainingContentText"]=> array(2) {
[0]=> string(1) "3"
[1]=> string(1) "5" }
["contextText_1"]=> string(0) ""
["contextText_2"]=> string(0) ""
["contextText_3"]=> string(0) ""
["contextText_4"]=> string(0) ""
["contextText_5"]=> string(0) ""
["submit_form"]=> string(6) "Submit"
}
array(11) {
["encounterName"]=> string(8) "Violence"
["encounterHint"]=> string(0) ""
["basicTrainingSectionSlide"]=> array(2) {
[0]=> string(1) "1"
[1]=> string(1) "6" }
["basicTrainingContentHeader"]=> array(2) {
[0]=> string(1) "2"
[1]=> string(1) "4" }
["basicTrainingContentText"]=> array(2) {
[0]=> string(1) "3"
[1]=> string(1) "5" }
["submit_form"]=> string(6) "Submit"
}
I would do something like this:
$i = 0;
$j = 0;
foreach($_POST['Sections'] as $order){
$fn = $order['encounterName'] . ".json";
$appText = "";
if(strcmp($order, "Section") == 0){
$appText .= "\t\t[\n";
$appText .= "\t\t\t\"Section\",\n";
$appText .="\t\t\t\"" . $order['basicTrainingSectionSlide'][$i] . "\"\n";
$appText .= "\t\t],\n";
file_put_contents($fn, $appText, FILE_APPEND);
$i++;
} elseif(strcmp($order, "Text") == 0){
$appText .= "\t\t[\n";
$appText .= "\t\t\t\"Text\",\n";
$appText .= "\t\t\t\"" . $order['basicTrainingContentHeader'][$j] . "\"\n";
$appText .= "\t\t\t\"" . $order['basicTrainingContentText'][$j] . "\"\n";
$appText .= "\t\t],\n";
file_put_contents($fn, $appText, FILE_APPEND);
$j++;
}
}
Since you are in a foreach loop and iterating over the array $_POST['Sections'], to call the elements of that array, you need to use $order. That is how you defined the loop. You kept calling $_POST and those indexes shouldn't exist.
If you were using $_POST, the first occurrence of encounterName would be located at $_POST['Sections'][0]['encounterName'] and would contain the string Violence. So, in the loop, $fn = $order['encounterName'].".json"; should be assigned Violence.json as a String.
I am unsure what the if statement is looking for. Since $order is an Array, not a String, strcmp() should return NULL. See notes here. Since both if statements would fail, your file would not be appended in either case. Please comment if you want to clarify that.
I tested the following on http://phpfiddle.org/lite :
<?php
$order = array();
if(strcmp($order, "Section")){
echo "Success";
} else {
echo "Fail";
}
?>
I got the following results:
E_WARNING : type 2 -- strcmp() expects parameter 1 to be string, array given -- at line 5
Fail
This code is untested.

Array element being added after key change

i am trying to sort out my array, just remove some duplicate elements etc... It all works great and looks like this when i output it
array(3) { ["addon_mat_3"]=> string(2) "15" ["addon_mat_7"]=> string(1) "7" ["addon_mat_15"]=> string(1) "9" }
The above is with this code
foreach ($new_shopping_list_array as $columnName => $columnData) {
if(is_numeric($columnName)){
unset($new_shopping_list_array[$columnName]);
}
if($columnName == 'addon_id'){
unset($new_shopping_list_array[$columnName]);
}
if($columnData == 0){
unset($new_shopping_list_array[$columnName]);
}
}
However, if i add the else as show below, which i need as it removes the first 10 characters from the array key, then i all of a sudden get a fourth element added to the array with key "0".
array(4) { [0]=> string(1) "9" [3]=> string(2) "15" [7]=> string(1) "7" [15]=> string(1) "9" }
This code
foreach ($new_shopping_list_array as $columnName => $columnData) {
if(is_numeric($columnName)){
unset($new_shopping_list_array[$columnName]);
}
if($columnName == 'addon_id'){
unset($new_shopping_list_array[$columnName]);
}
if($columnData == 0){
unset($new_shopping_list_array[$columnName]);
}else{
$new_columnName = substr($columnName, 10);
unset($new_shopping_list_array[$columnName]);
$new_shopping_list_array[$new_columnName] = $columnData;
}
}
Everything else is great, apart from that fourth element added, what am i doing wrong,
Thanks for any and all help
That code should work, but you could do the whole thing in a few less lines:
$flipped = array_flip($new_shopping_list_array);
foreach ($flipped as $value => &$key) {
if($key == "addon_id" || is_numeric($key) || $value == 0) {
unset($flipped[$value]);
} else {
$key = substr($key,10);
}
}
$new_shopping_list_array = array_flip($flipped);

Categories