Build string from array omitting empty or NULL values in PHP - php

I am trying to build an array from a list of URL parameters to transact with a database. Basically I have several functions that do different things. (Insert, Update, etc) so depending on what it is specifically trying to do it may not need ALL columns in the database at all times.
So say I have these 5 potential parameters that might get passed: id,gr,bl,yw,re
If I am inserting a new row all 5 coulmns need some sort of value. If I am say updating the bl column then I only pass the id and bl parameters.
So I am doing this to build the query string(not actual code just example):
foreach($_GET as $key => $value) {
$key = strtolower($key);
if (preg_match($acceptedGETS,$key)) $$key = $value;
}
$table_col = array (
'p_id' => $_GET['id'],
'p_gr' => $_GET['gr'],
'p_bl' => $_GET['bl'],
'p_yw' => $_GET['yw'],
'p_re' => $_GET['re']);
$vstring = implode(',' , $table_col);
Now this works perfectly, as long as ALL variable keys have a value (or not NULL). My question is, how can I build a string from an array, but exclude the keys that don't get passed values. Right now if keys are missing values I get this for example:
URL: http://www.mysite.com/myscript.php?id=4&re=9 would get me:
4,,,,9
when I need to just get 4,9
Thanks!

Use $get = array_filter($_GET) and it will get rid of empty or null values.

Try
$vstring = "";
$acceptedGETS = array("id", "gr", "bl", "yw", "re");
$values = array();
foreach ($_GET as $key => $value)
{
$k = strtolower($key);
if (!in_array($k, $acceptedGETS))
continue;
$values[$k] = $value;
}
$vstring = implode(",", $values);

Here is another way using just filter_input_array and set of filters
$args = array(
'id' => FILTER_VALIDATE_INT,//if it is an integer
'gr' => FILTER_SANITIZE_STRIPPED,//in case it is a string
'bl' => FILTER_SANITIZE_STRIPPED,
'yw' => FILTER_SANITIZE_STRIPPED,
're' => FILTER_SANITIZE_STRIPPED,
);
//Filter array values to avoid bad data if nothing found NULL returned
$myInputs = filter_input_array(INPUT_GET, $args);
//if it is an array join it with coma
if(is_array($myInputs))
$myInputs = implode(',', $myInputs);

Related

How to loop this array and save to database?

I have this array to save to database:
{"i_barcode_id":["3","3"],"i_barcode_sn":["8999999565404","6933412700043"]}
how do I save it to DB so the databse should be like this.
i_barcode_id i_barcode_sn
3 8999999565404
3 6933412700043
this is my current script.
foreach($myarray as $row){
$dataadd_sto_d = array (
'ID' => $rows['i_barcode_id'],
'SN' => $rows['i_barcode_sn']
);
$insertsto_d = $this->MWarehouse->add_sto_d($dataadd_sto_d); //insert script
};
The script failed to save to database. I do not know why. any
Use this tested working
$key = array();
$value = array();
foreach($myarray as $row){
$id => $rows['i_barcode_id'],
$sn => $rows['i_barcode_sn']
array_push($key, $id);
array_push($value, $sn);
}
$insert_data = array_combine($key, $value);
return $this->MWarehouse->add_sto_d($insert_data);
Note
array_combine() will now throw a ValueError if the numberof elements for each array is not equal; previously this function returned false instead.
You have some typos in your Code like foreach(... as $row) and later you want to access $rows
My Attemp would be, to grap i_barcode_id or i_barcode_sn to loop and take the value index to get the data from the other array.
Example:
//true at the end, cause i have something against stdClass without any reason
$myarray = json_decode('{"i_barcode_id":["3","3"],"i_barcode_sn":["8999999565404","6933412700043"]}',true);
foreach($myarray['i_barcode_id'] as $key => $val){
$insertArray=array(
"ID" => $val,
"SN"=>$myarray['i_barcode_sn'][$key]
);
//Your Insert Script
};

Insert key value - array in array

I am getting some values (domain names) from a _POST which I have to insert into an "Array in an Array". The array is called $postValues["domainrenewals"] and the I need to create another array inside this one in the format:
domainname => 1 (where 1 is the number of years).n
My code:
foreach ($_POST['renewthesedomains'] as $key => $value) {
$postValues["domainrenewals"] = array($value => "1");
}
var_dump ($postData);
The var_dump shows that only the last $key -> $value pair is being inserted into $postValues["domainrenewals"]
Any help, much appreciated.
In each pass of the foreach loop you're redefining $postValues["domainrenewals"] so of course only the last one is saved... Try doing this:
$postValues["domainrenewals"] = array();
foreach ($_POST['renewthesedomains'] as $key => $value) {
$postValues["domainrenewals"][$value] = "1";
}
If you need to add another value to the array I'm assuming it's information of the domain, so you would do something like:
$postValues["domainrenewals"][$value]['your_first_value'] = "1";
// Then for your other value
$postValues["domainrenewals"][$value]['renewalpriceoverride'] = 285.00;
Try This:
$postValues = array();
$arr=array();
foreach ($_POST['renewthesedomains'] as $value) {
$arr["domainrenewals"]=$value;
$arr["no_of_years"]=1;
$postValues[] = $arr;
$arr=array();
}

adding values to php multidimensional associative array

Hi in the code below I want to add an extra value for the associative array. For each queryresult in wich elements ["Nietaanwezig"] and ["Aanwezig_diner"] both are 0 I want to add the element ["Nietingevuld"] and set it's value to 1, otherwise i want to add the element ["Nietingevuld"] and set it's value to 0. Albeit I have tried a lot of options, I don't seem to ge a good solution.
// numerically indexed array of places
$namen = [];
$queryresult = [];
// TODO: search database for places matching $_GET["geo"]
$search = $_GET["zoekopdracht"];
if ($search = "diner")
{
$namen = query ("SELECT * FROM gasten WHERE Typegast = 1");
foreach ($namen as $naam)
{
$queryresult [] = [
"Voornaam" => $naam["Voornaam"],
"Achternaam" => $naam["Achternaam"],
"Nietaanwezig" => $naam["Nietaanwezig"],
"Aanwezig_diner" => $naam["Aanwezig_Diner"],
];
}
Don't do it all in a single stage then. Build the new child array, modify it as necessary, THEN insert it into the parent array:
$temp = array('Voornaam' => $naam['Voornaam'], etc....);
if (whatever you want to check) {
$temp['something'] = 'else';
}
$queryresult[] = $temp;

Find matching key in two associate arrays?

I'm using codeigniter and I have a returned associated array from db like this:
$result = ['name'=>'john', 'author'=>'smith', 'year'=>2011 ];
And a long list of translated title for the keys saved as an array like this:
$lang = ['name'=>'名字', 'author'=>'作者', 'year'=>'年份', ... ];
I wanted to compare the key of $result to $lang, if a key was used in $result, get its translated title. And at the end, construct an array including all three English title, translated title, and the value:
$lang_result = ['name' =>['名字', 'john'],
'author' =>['作者', 'smith'],
'year' =>['年份', 2011] ]
$data['result'] = $lang_result;
I'm storing into this format because once I passed in these data into views, I wanted to be able to call each one by name
echo "{$result['name'][0]}: {$result['name'][1]} "; // 名字: john
echo "{$result['author'][0]}: {$result['author'][1]} ";
So far I could only achieve this by using foreach -> switch statement
$lang_result = [];
foreach ($result as $key=>$value ) {
switch ($key){
case 'name':
array_push ($lang_result, [ $key => ['名字', $value] ]);
break;
case 'author':
array_push ($lang_result, [ $key => ['作者', $value] ]);
break;
}
}
But as the translated array gets longer, the switch statement will be ridiculously out of hands. What is a better way to simplify this?
As Dan mentioned array_merge_recursive may be what you want. In case you have other logic you need to implement here it is unrolled:
$result = ['name'=>'john', 'author'=>'smith', 'year'=>2011];
$lang = ['name'=>'名字', 'author'=>'作者', 'year'=>'年份'];
$lang_result = [];
foreach ($result as $key=>$value) {
if (array_key_exists($key, $lang)) {
$lang_result[$key] = [$lang[$key], $value];
}
}
// these are the same (for now)
print_r($lang_result);
print_r(array_merge_recursive($lang, $result));
Try using array_merge_recursive
$newArray = array_merge_recursive($result, $lang);
You need to store the keys you want into an array and then do it like so.
$lang_result = array();
$result = ['name'=>'john', 'author'=>'smith', 'year'=>2011 ];
$lang = ['name'=>'名字', 'author'=>'作者', 'year'=>'年份'];
$keys = array('name','author','year');
foreach($keys AS $key){
if(isset($result[$key]) && isset($lang[$key])){
$lang_result[$key] = array($result[$key],$lang[$key]);
}
}

Drupal 6 $key => $value form #options array built using while loop where $key = $value

I'm trying to build an array of $key => $values using a while loop where the $key is equal to the value, from a db_query. I think the syntax isn't correct
function _form(){
$person = db_query("SELECT name FROM {person}");
$columnValues = Array();
while ($row = db_fetch_array($person) ) {
$columnValues[] = array($row['name']=> $row['name']);
}
.
.
.
I have a few questions.
do i need to create a key to pull out the actual 'select' menu item value?
if i need to create a key, is there a way in the while loop to not create a new array for each element that is keyed by its same value (eg. apple => apple)
what is the correct way to pull out values from checkboxes and from select so i get a string and not an ordered number? (eg. form_values['value']['select_name'] , form_values['value']['checkboxes_name'] so that first returns selected item 'apple' and second gives checked item 'apple'.) ... i like apples.
You seem to be making a mistake here - in the key value pair, the value cannot be an array
while ($row = db_fetch_array($person) ) {
$columnValues[] = array($row['name']=> $row['name']);
}
should be
while ($row = db_fetch_array($person) ) {
$columnValues[$row['name']] = $row['name'];
}
Answers:
Yes, you should always add a key value pair - as value is what gets displayed and key is what gets submitted in the form submit.
Yes the above explains how you should create key => value pair and not an array of key => value pairs for each item.
Individual checkbox items have values and you can set the value of checkbox to be the same as that of the display.

Categories