Array element being added after key change - php

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);

Related

PHP Optgroup in Foreach

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

Check if string exists inside a json foreach loop

I am trying to check if a value exists inside an foreach loop from a decoded json response and compare it to my own string. I need to set $response_array['status'] to "Allowed" if $domain_to_check value exists inside the $key_info['registered_domain'] array. I tried to use in_array php function to check if value exists, however i had no success and i keep getting back "Not Allowed - Domain not listed" response even when the value is inside the array. I think that the problem is with my foreach loop but for the sake of me i can't figure whats wrong.
$domain_to_check = 'domain-name.com';
$data = json_decode($returnCheckValue,true);
$key_response = $data['result'];
if ($key_response == 'success'){
foreach ($data['registered_domains'] as $key_domain_info) {
$key_listed_domain = $key_domain_info['registered_domain'];
if ($key_response == 'success' && in_array($domain_to_check, $key_listed_domain)) {
$response_array['status'] = 'Allowed';
}
else {
$response_array['status'] = 'Not Allowed - Domain not listed';
}
}
}
else {
$response_array['status'] = 'Not Allowed - Wrong Key';
}
echo json_encode($response_array);
Here is how my var_dump(); of the $data looks like
array(9) { ["result"]=> string(7) "success" ["max_allowed_domains"]=> string(1) "3" ["registered_domains"]=> array(2) { [0]=> array(5) { ["id"]=> string(2) "60" ["lic_key_id"]=> string(2) "51" ["lic_key"]=> string(13) "93248cqkdj21as" ["registered_domain"]=> string(19) "domain-name-2.com" ["item_reference"]=> string(1) "1" } [1]=> array(5) { ["id"]=> string(2) "58" ["lic_key_id"]=> string(2) "51" ["lic_key"]=> string(13) "93248cqkdj21as" ["registered_domain"]=> string(14) "domain-name.com" ["item_reference"]=> string(3) "443" } } }
Relate below code with your code. This code is working.
$domain_to_check = "domain-name.com";
$test = array("registered_domains" => array("registered_domain" => "domain-name-2.com"), array("registered_domain" => "domain-name.com"));
foreach($test as $val) {
if($val['registered_domain'] == $domain_to_check) {
$result = 'success';
break;
} else {
$result = 'failure';
}
}
echo $result;
Use php strpos
$domainStringFound = strpos($key_listed_domain, $domain_to_check);
if ($key_response == 'success' && $domainStringFound !== false) {
$response_array['status'] = 'Allowed';
}

output of array always equals 'i'

I have the variable $request. If i do vardump($request), I get the output of:
array(7) {
["controller"]=> string(5) "index"
["action"]=> string(5)"index"
["module"]=> string(7) "default"
[2]=> array(8) {
["g_goal_list_id"]=> string(3) "127"
["textgoal"]=> string(9) "eats food"
["task_0"]=> string(1) "0"
["value_0"]=> string(5) "pukes"
["task_1"]=> string(1) "0"
["value_1"]=> string(0) ""
["task_2"]=> string(1) "0"
["value_2"]=> string(0) ""
}
[3]=> array(10) {
["g_goal_list_id"]=> string(3) "128"
["textgoal"]=> string(9) "goes home"
["task_0"]=> string(1) "0"
["value_0"]=> string(20) "but never comes back"
["task_1"]=> string(1) "0"
["value_1"]=> string(14) "stays home now"
["task_2"]=> string(1) "0"
["value_2"]=> string(0) ""
["task_3"]=> string(1) "0"
["value_3"]=> string(0) ""
}
["submit"]=> string(4) "Save"
["task"]=> string(1) "5"
}
which is all correct. However, I'm trying to use a foreach statment to grab values from the $request array and put them into a data array, and then submit that to the mysql db...
foreach($request as $currentrow){
//skips row if the field is empty
if(strlen($currentrow['value']) < 1)//need to make sure I've defined $currentrow['value']
continue;//skips row with empty field
//I only need to grab the value/list_id/account_id from the form
$data = array('value' => $currentrow['value'],
'g_goal_list_id' => $currentrow['g_goal_list_id'],
'account_id' => g_getAccountId(),
);
var_dump($data);
However, when I var_dump($data); my output looks like this:
array(3) { ["value"]=> string(1) "i" ["g_goal_list_id"]=> string(1) "i" ["account_id"]=> string(1) "1" }
array(3) { ["value"]=> string(1) "S" ["g_goal_list_id"]=> string(1) "S" ["account_id"]=> string(1) "1" }
array(3) { ["value"]=> string(1) "5" ["g_goal_list_id"]=> string(1) "5" ["account_id"]=> string(1) "1" }
The only thing that is correct in that var_dump($data) is the ["account_id"]
I'm thinking that my loop is incorrect, and I'm pretty bad with loops. Sooooo yeah, hopefully I included enough information. Thank you.
What you need is something like this:
foreach($request as $k=>$currentrow)
{
$hit = false;
$data = array();
// Only look for sub-arrays
if(is_array($currentrow))
{
foreach($currentrow as $k2=>$v2)
{
$explode = explode('_', $k2);
if($explode[0] === 'value') //need to make sure I've defined $currentrow['value'] regardless of suffix
{
$hit = true;
$data = array(
'value' => $v2,
'g_goal_list_id' => $currentrow[$k]['g_goal_list_id'],
'account_id' => g_getAccountId(),
);
continue;
}
}
}
if($hit === false)
{
continue;
}
var_dump($data);
}
This element: $currentrow['values'] does not exist (check your logs, you should see notices). Neither does $currentrow['g_goal_list_id'].
You loop through an array with all different elements, the first being a string, with value index. When you then take that string and subscribe that with values, it throws a warning, but then takes the first element.
To clarify, a some CLI code:
php > $a="abcd";
php > echo $a["foo"];
PHP Warning: Illegal string offset 'foo' in php shell code on line 1
a
If you want to loop over keys and values, do like this:
foreach($request as $key=>$value) {
}
That being said, I think a loop is not what you want, you do not have straighforward table-like data.
Huge thanks to #MonkeyZeus. I kept on getting an array that had the proper keys but all the values were null. Turns out I just needed to put my var_dump($data) inside of my loop, because when it was on the outside it was returning only the last array it looped thorough. On my form the last values it loops through were empty fields, that are meant for the user to add input. Also, I had to change 'g_goal_list_id' => $currentrow[$k]['g_goal_list_id'] to just 'g_goal_list_id' => $currentrow['g_goal_list_id']
foreach ($request as $k=> $currentrow) {
$hit = false;
$data = array();
if(is_array($currentrow)){
foreach ($currentrow as $k2 => $v2) {
$explode = explode('_', $k2); //blows off the suffix of the $key
//var_dump($explode);
//$explode=substr($explode,2);
//echo $k2;
//echo '******';
//echo $v2;
echo $explode[0];
echo '/';
if($explode[0] == 'value'){
//echo "[" . $currentrow['g_goal_list_id'] . "]";
$hit = true;
$data = array(
'value' => $v2,
'g_goal_list_id' => $currentrow['g_goal_list_id'],
'account_id'=> g_getAccountId(),
);
continue;
}
var_dump($data);
}
}
if ($hit === false){
continue;
}
break;
}

find / select specified ID in array php

i have array with database, and have to select only this items what have "tid" = 1
array(3) {
[1]=>
array(4) {
["tid"]=> "1"
["title"]=> "Google"
["url"]=> "http://google.com/"
["description"]=> "A very efficient search engine."
}
[2]=>
array(4) {
["tid"]=> "2"
["title"]=> "Facebook"
["url"]=> "http://facebook.com/"
["description"]=> "Trade securities, currently supports nearly 1000 stocks and ETFs"
}
[3]=>
array(4) {
["tid"]=> "1"
["title"]=> "Yandex"
["url"]=> "http://yandex.ru/"
["description"]=> "Another efficient search engine popular in Russia"
}
}
how can i select only this items from array what have "tid" = 1?
<?php
$final_arr = array();
foreach($tid_arrs as $tid_arr){
if($tid_arr['tid'] == 1){
$final_arr[] = $tid_arr;
}
}
print_r($final_arr);
?>
$filteredArray = array();
for($i = 0, $end = count($array);$i < $end;i++)
{
if($array[$i]["tid"] === "1")
{
$filderedArray[] = $array[$i];
}
}
That way $filteredArray will contain solely the items with tid 1;
Try array_filter function: http://php.net/manual/en/function.array-filter.php this should help.
print_r(array_filter($array, "filter_function"));
function filter_function($element){
return (int)$element['tid'] === 1;
}
let's say you starting array is $arr.
$result = array();
foreach ($arr as $arrItem) {
if ((array_key_exists('tid', $arrItem)) && ($arrItem['tid'] == "1")){
$result[] = $arrItem;
}
}
$result should be what you are excepted.

How to build this kind of Logic using arrays in PHP

I have an array which consists of this set of items
array(3) {
[0]=>
array(4) {
["Field1"]=>
string(8) "80000007"
["Field2"]=>
string(16) "O70000006"
["Field3"]=>
string(0) ""
["Field4"]=>12345
string(0) ""
}
[1]=>
array(4) {
["Field1"]=>
string(8) "80000008"
["Field2"]=>
string(16) "O70000007"
["Field3"]=>
string(0) ""
["Field4"]=>78965
string(0) ""
}
[2]=>
array(4) {
["Field1"]=>
string(8) "80000009"
["Field2"]=>
string(16) "H80000006"
["Field3"]=>
string(0) ""
["Field4"]=>12345
string(0) ""
}
}
Now my question is Iam trying to display only the items once from array or trying to filter the array in such a way if the "Field2" has
a value starting with "O" or "H" and their "Field4 " value should be different . If the "Field4" value is same for the each of the row
then we dont display that row or array item . For eaxample from the above array we will get 2 items as follows
1)80000007 O70000006 12345
2)80000008 O70000007 78965
//we are not displaying the 3rd Item
because The "Field4 " is same . we
display only once
foreach ($resultset as $key => $value){
echo $key."<br>"; /// outputs 0,1,2
echo $value['Field2']."<br>"; // outputs O70000006, O70000007, H80000006
}
function getField2_removeDupeField4($arr){
$f4 = array();
$f2 = array();
foreach($arr as $array){
if(in_array($array['Feild4'], $f4){ continue; }
$firstChar = substr($array['Feild2'], 0, 1);
if($firstChar == 'O' || $firstChar == 'H'){
$f2[] = $array;
$f4[] = $array['Feild4'];
}
}
return $f2;
}
So to get the array you want:
$new_arr = getField2_removeDupeField4($orig_arr);
So... you just want some way to skip rows whose Field4 has already been printed?
Set up an array to hold all the previously printed Field4s, and check against that before printing anything. Something like this:
$field4s = array();
foreach ($resultset as $key => $value){
$field4 = $value['Field4'];
if (($field4[0] == 'O' || $field4[0]=='H') && !in_array($field4 , $field4s) {
array_push($field4s, $field4);
echo $field4;
}
}

Categories