Adding String to Value in PHP Array - php

I have an HTML form which collects values in a format needed for a certain task. After completing the task, I would like to perform an additional task using the same values from the form without having the user enter the information in a second time.
The problem that I am running into is that the second task requires two of the fields to be formatted differently when they are sent to their destination.
Here is the array on the second script that is being sent where the keys on the left are being assigned the values on the right by the values from the form.
$contactFields = array(
// field name in myServer => field name as specified in html form
'aaaaaaaa' => 'email',
'bbbbbbbb' => 'stuff',
'cccccccc' => 'morestuff',
'dddddddd' => 'blah',
'eeeeeeee' => 'blahh',
'ffffffff' => 'blahh',
'gggggggg' => 'tobacco', //tobacco use
'hhhhhhhh' => 'amount', //face amount
);
What I am trying to do is add the string ',000' to the value of 'amount' taken from the user input. Again, I cannot just change the value on the HTML form because I need the value formatted differently for the first script.
I have tried
'hhhhhhhh' => 'amount'.',000',
No bueno. I also tried a similar method before the array, but to no avail.
For the field receiving the value of 'tobacco', I am trying to convert it from a 0 or 1 value, to a yes or no value. I tried this
if ($tobacco == 1) {
$tobacco = "yes";
} else if ($tobacco == 0) {
$tobacco = "no";
} else {
$tobacco = "?";
};
But that just caused the script to return a null value.
$Tobacco was originally assigned above the contactFields array as such
//
Assigns variables to input fields
$aaaaaaaa = $_POST['email'];
$bbbbbbbb = $_POST['aaaaaaaa'];
$cccccccc = $_POST['bbbbbbbb'];
$dddddddd = $_POST['cccccccc'];
$eeeeeeee = $_POST['dddddddd'];
$ffffffff = $_POST['eeeeeeee'];
$gggggggg = $_POST['tobacco'];
$hhhhhhhh = $_POST['amount'];
Any suggestions? Thanks. PHP is not my strongpoint.

If you want to change the value of the array item you can do it this way:
$contactFields['hhhhhhhh'] = $contactFields['hhhhhhhh'].",000";
echo $contactFields['hhhhhhhh'];
// outputs
// amount,000
$contactFields['gggggggg'] = ($contactFields['gggggggg'] == '1' ? 'yes' : 'no');
echo $contactFields['gggggggg'];
// outputs
// yes
or you can set variables if you don't want to alter your array:
$newAmmount = $contactFields['hhhhhhhh'].",000";
echo $newAmount;
// outputs
// amount,000
$newTobacco = ($contactFields['gggggggg'] == '1' ? 'yes' : 'no');
echo $newTobacco;
// outputs
// yes
But as was mentioned, if 'amount' is truly a number, use number functions and don't store it as a string.

Related

How to convert json checked checkbox data to a list?

How would I convert a json string that contains checkbox values to a list?
For example, I have the following json string :
{"User1":"Checked","User2":"","User3":"Checked"}
I want to pull a list from the above data, and assign it to a variable. The list should of course, only output the checked elements as such :
User1
User3
and ignore the unchecked items.
Is this possible?
Original thought was to do this in a jqgrid layout, original question here :
https://stackoverflow.com/questions/34615244/best-way-to-do-jqgrid-with-json-strings
Full Array Code(processing side) :
$status = $data['data-invoice-status']; // this is an array
$status_array = array(); // create new array
$status_names = array(1 => "Service Call",2 => "Estimate",3 => "Bid Accepted",4 => "Unstaged",5 => "Staged",6 => "Assigned",7 => "In Progress",8 => "Job Complete",9 => "Billed");
for($i = 1; $i <= 9; $i++){ // loop from 1 to 5
if(in_array($i, $status)){ // if value exists (has been selected), stack 'checked', if not, stack ''.
$status_array[$status_names[$i]] = "checked";
} else {
$status_array[$status_names[$i]] = "";
}
}
$status_json = mysqli_real_escape_string($this->_con, json_encode($status_array)); // encode the array into JSON and then escape it.
I then save $statusd into my db whenever anyone updates the form, but no data is transferred.
Decode the JSON to an array, then get the keys where the value equals 'Checked':
$list = array_keys(json_decode($json, true), 'Checked');
Or possibly to filter out empty items instead of searching for 'Checked', but then you still have keys instead of values:
$list = array_filter(json_decode($json, true));
Then implode() or foreach() or whatever to work with the array.
Based on your edits:
You really should use a related table and save each user to a new row, but
You're encoding then adding slashes mysqli_real_escape_string and then trying to decode it again
Assuming you're not going to do #1 then just this:
$statusd = mysqli_real_escape_string($this->_con,
implode(",", array_keys($status_array, 'Checked')));

convert back the $_GET array to the original URL query

I have an associative array called $new_get which comes from the original array of $_GET. The difference is that I modified somes of the keys and values that I will after need to echo to make a new URL.
I simply want to convert back this $new_get to it's original form, like :
?something=this&page=2
My $new_get looks like :
$new_get = array (
'something' => 'this',
'page' => '2'
);
simply do that :
$query = "?" .http_build_query($new_get);
if your $new_get is built the same way than $_GET.
Here is a function of my own to make a new URL Query based on the actual one :
// the array_of_queries_to_change will be numbered, the values in it will replace the old values of the link. example : 'array_of_queries_to_change[0] = "?page=4";'.
// the returned value is a completed query, with the "?", then the query. It includes the current page's one and the new ones added/changed.
function ChangeQuery($array_of_queries_to_change)
{
$array_of_queries_to_change_count = count($array_of_queries_to_change); // count how much db we have in total. count the inactives too.
$new_get = $_GET;
$i0 = 0;
// echo "///" .($get_print = print_r($_GET, true)) ."///<br />";
// echo "///" .($get_print = print_r($new_get, true)) ."///<br />";
while ($i0 < $array_of_queries_to_change_count)
{
$array_of_keys_of_array_of_queries_to_change = array_keys($array_of_queries_to_change);
$new_get[$array_of_keys_of_array_of_queries_to_change[$i0]] = $array_of_queries_to_change[$array_of_keys_of_array_of_queries_to_change[$i0]];
$i0++;
}
$query = "?" .http_build_query($new_get);
return $query;
}
/*// example of use :
$array_of_queries_to_change = array (
'page' => '2',
'a key' => 'a value'
);
$new_query = ChangeQuery($array_of_queries_to_change);
echo $new_query;
*/

Conditional statement in an json encoded array

I'm showing a "Review Your Order:" part of a page with the success callback of a json_encode array. I probably said that completely wrong in technical terms but hopefully you can see what I'm trying to do.
Part of the PHP processing page...
$results = array(
'roomname' => $_POST['roomX'],
'qty' => $_POST['qtyX'],
and I want the results to be returned as...
Room Name: Whatever is returned. (notice the label "Room Name: ")
But I only want the label to show IF the POST has a value assigned.
Example of how I think it should look but it's not working..
$results = array(
'roomname' => if (!$_POST['roomX']=='' { echo 'Room Name: ' .$_POST['roomX'];},
Does that make sense? There are dozens of options for each order and I don't want "Label: " in front of a bunch of values that are empty.
EDIT: Added code from answer below.
// beginning of array
$results = array(
'roomname' => $_POST['roomX'],
'qty' => $_POST['qtyX'],
// more code...
// end of array.. remember not to have a comma on this last one.
);
// pasted answer between the array ending and the json_encode line.
if ($_POST['roomX'] != ''){
$results['roomname'] = "Room Name: ".$_POST['roomX'];
}
$json = json_encode($results);
echo $json;
here is one way, you can user a Ternary operation
$results = array(
'roomname' => $_POST['roomX']==''? 'Room Name: '.$_POST['roomX']: '',
);
this will add a blank string if the value is empty
the other way will be to just add the value later;
$results = array(...);
if ($_POST['roomX'] != ''){
$results['roomname'] = $_POST['roomX']
}
$results = array();
if (isset($_POST['roomX'])) {
$results[] = array(...);
}
if there's no post value, you just end up with an empty array.
you can make an if statement before assigning any data to roomname like so
$result = array(
'roomname' => ($_POST['roomX'] !== '')? 'Room name: '.$_POST['roomX']:''
);
The thing I used here is a shortend if statement and works as following: (if statement)? true : false;
I hope this will help you.

add value into userdata array

I thought this would be simple but I cant seem to get it to work. All I want to do is to add a value into a userdata array. If a value is already in the viewed_news_items array I do not want to replace it.
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true,
'viewed_news_items' => array()
);
$this->session->set_userdata($data);
insert value into viewed_news_items array
$a = array($desk_id => $desk_id);
$this->session->set_userdata('viewed_news_items', $a);
You're using $desk_id as both the key and value, meaning unless you already have the value of $desk_id, you won't be able to look it up in the array.
Instead of this:
$a = array($desk_id => $desk_id);
You probably wanted to do this:
$a = array('desk_id' => $desk_id);
That is, use the string 'desk_id' as the key whose corresponding value is $desk_id.
Is there a way to have the 'desk_id' just as an auto number so each time the code is executed another value is added instead of replacing 'desk_id'?
You can push items onto the end of an array via array_push($array, $value) or $array[] = $value. PHP will automatically assign the next numeric ID as the index for the new array element.
In your current scenario, you'll have to pull the existing list of IDs out of the session, append an ID to it, and then put it back into the session:
# pull the existing IDs out of the session
$viewed_news_items = $this->session->userdata('viewed_news_items');
# on first load, the array may not be initialized
if (!is_array($viewed_news_items))
$viewed_news_items = array();
# append $desk_id to the list of viewed items
$viewed_news_items[] = $desk_id;
# put the new list back into the session
$this->session->set_userdata('viewed_news_items', $viewed_news_items);
invoke the type of data you retrieved from session
and use it as you want.
$ID = 123;
$data = (array)$this->session->userdata("session_name");
$data[] = $ID;
$this->session->set_userdata("session_name",$data);

How to shorten php code, in multiple combination of form result

I have a php page that contains a form with 7 drop down boxes.
The problem is that the 0 to 6 boxes may be unselected.
It would be a lot of work to make a switch with a case for every combination.
What other method can i use?
thanks,
Sebastian
EDIT
For each combination i have to make different queries that contain only the selected items from the drop-boxes.
Ex. If the user selects 3 from the 7, the query has to pass 3 conditions.
EDIT2
I don't know what the values of the drop-boxes are. Because they are built up using an mysql query in a while statement
SOLUTION
I've found a solution that should work. I haven't tested it yet.
First of all i want to check if what is selected in the drop-boxes.
`If($_POST[telefon]="empty"){$tel=""}
else{$tel="WHERE telefon =' "}`
after this i can concatenate the $tel string with the $_POST['telefon'] string.
$query_tel=$tel.$_POST['telefon']." ' ";
Final query string would look like this $query="SELECT * table ".$query_telefon." ,".$query_ziua....(and so on)
Of course i have to be very careful with the query that will result, for missing commas, apostrophes and so on. But i guess it's the simplest way.
UPDATED
ASSUMPTION: the point here is you want reduce code in relation with number of query!
PREMISE: the use of switch or and/if are both valid approach anyway!
for reducing your code to one line for all the queries, your SQL column name and SELECT html element should be called the same, like:
t_apple VARCHAR(255) NOT NULL,
t_peach VARCHAR(255) NOT NULL,
t_strawberry VARCHAR(255) NOT NULL,
...
<select name="t_apple"></select>
<select name="t_peach"></select>
<select name="t_strawberry"></select>
...
try this:
if ( isset($_POST['submit']) ) {
$form_button = array_pop($_POST); //remove the submit button val
$new_array = array_filter( $_POST , 'strlen'); //remove empty value from $_POST
foreach( $new_array as $key => $val ) {
//optionaly make some other check here if ($val != '---')
// "INSERT INTO {$key} VALUES ( {$val} )"
}
}
You can decide to preset the values and then overwriting them:
$array(
'dropdown1' => 'value1',
'dropdown2' => 'value2',
'dropdown3' => 'value3',
'dropdown4' => 'value4',
'dropdown5' => 'value5',
'dropdown6' => 'value6'
)
$array = $_POST;
This way you can set the default values and just overwrite the array with the post array send from the form.
EDIT:
if you set the empty value to 'empty' like this:
<select name="dropdown[dropdownnamehere]">
<option value='empty'>---</option>
</select>
You will be able to loop trough the values and only select the set ones
foreach($_POST['dropdown'] as $item => $value)
{
if($value != 'empty')
{
//create a mysql part here
}
}

Categories