I have an array which looks like:
$diseases= [
['letter' => 'A' , 'options' => "<div ..."],
....
];
And I pass the letter as a parameter in the URL. It works. But I can't understand how to make it print the options that correspond to the letter on the page. Thanks for reading.
You could put it in the session:
session_start();
$_SESSION['array_name'] = $array_name;
Or if you want to send it via a form you can serialize it:
<input type='hidden' name='input_name' value="<?php echo htmlentities(serialize($array_name)); ?>" />
$passed_array = unserialize($_POST['input_name']);
Try something like this:
<?php
$diseases = [
'A' => "<div>A</div>",
'B' => "<div>B</div>",
];
$letterAction = isset($_GET['letterAction']) ? $_GET['letterAction'] : ''; //if the letterAction parameter is defined in the URL, then get it's value
if (isset($diseases[$letterAction])) {
//if the letterAction is available in the array, then print it's value
//i.e. isset($diseases["A"]) would return true but isset($diseases["C"]) would return false in this case
echo $diseases[$letterAction];
}
You can use sessions to store information to be used on all pages:
session_start();
$_SESSION['diseases'] = $diseases; // store information to key data
On the other pages you use:
session_start();
print_r($_SESSION['diseases']);
If you only want the data to be set for 1 specific page you can use http_build_query()
$diseases = ['diseases' => $diseases];
$str = http_build_query($diseases);
echo "<a href='yourpage.php?$str'>click</a>";
Now on the next page you simply use:
parse_str($_GET['diseases'], $diseases);
print_r($diseases);
Related
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.
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;
*/
I need to update a json list of object via url post data. For example, with url:
http://myweb.com/index.php?name=Peter&surname=Brown
in php, using get method:
$name = $_GET["name"];
$surname = $_GET["surname"];
$json = array();
$json["nombre"] = $name;
$json["lat"] = $lat;
$data[] = $json;
$json_end= json_encode($data);
and json_end efectively is done like I want:
[{"name":"Peter","surname":"Brown"}]
My question is about how I can do it incrementing the json, in order to build an array like:
[{"name":"Peter","surname":"Brown"}]
[{"name":"newname","surname":"newsurname"}]
// and so on
each time user use the url with new parameters.
Do I need to write to a file, or to database? Any tips will be apreciated.
The idea is to be able that any user can add some dat using url. I tried to store the json to a fiel but the storing is durable only along the current session.
<?
/* This needs to be at the top of your file, without ANYTHING above it */
session_start();
/* ... */
if(!array_key_exists('entries', $_SESSION))
{
$_SESSION['entries'] = array();
}
$_SESSION['entries'][] = array("name" => $_GET["name"], "surname" => $_GET["surname"]);
$json_string = json_encode($_SESSION['entries']);
This would produce a single JSON. However I don't know whether you meant to or not, but your output is a series of separate JSONs. You could do this by replacing the last line above with:
$json_string = '';
foreach($_SESSION['entries'] as $entry){
$json_string.= json_encode($entry) . "\n";
}
You would also probably want a way to reset/empty the array. In which case I'd change the if test from:
if(!array_key_exists('entries', $_SESSION))
to:
if(!array_key_exists('entries', $_SESSION) || array_key_exists('reset', $_GET))
Which you could use by visiting
http://myweb.com/index.php?reset
Edit: If somewhere you add the following code:
foreach($_SESSION['entries'] as $id=>$entry){
printf("%2d: %s\n", $id, json_encode($entry));
}
You'll get a list of the json elements enumerated by their respective keys. For example, it might look like:
0: "[{\"name\":\"Peter\",\"surname\":\"Brown\"}]"
1: "[{\"name\":\"newname\",\"surname\":\"newsurname\"}]"
2: "[{\"name\":\"George\",\"surname\":\"Washington\"}]"
3: "[{\"name\":\"John\",\"surname\":\"Adams\"}]"
If you then add the following code:
if(array_key_exists('del', $_GET) && is_numeric($_GET['del']))
{
$key = (int)$_GET['del'];
if(array_key_exists($key, $_SESSION['entries']))
{
unset($_SESSION['entries'][$key]);
}
else
{
printf('<strong>ERROR: $_GET['del'] = %d but $_SESSION['entries'][%d] doesn't exist.</strong>', $key, $key);
}
}
you'll be able to delete individual json entries by specifying id as the del GET parameter.
For example,
http://myweb.com/index.php?del=2
would delete the entry corresponding to '[{"name":"George","surname":"Washington"}]';
And the remaining entries would be:
0: "[{\"name\":\"Peter\",\"surname\":\"Brown\"}]"
1: "[{\"name\":\"newname\",\"surname\":\"newsurname\"}]"
3: "[{\"name\":\"John\",\"surname\":\"Adams\"}]"
4: "[{\"name\":\"Thomas\",\"surname\":\"Jefferson\"}]"
Just make a nested array of users:
$data = array (
0 => array("name"=>"Peter","surname"=>"Brown"),
1 => array("name"=>"newname","surname"=>"newsurname")
);
echo json_encode($data);
// [{"name":"Peter","surname":"Brown"},{"name":"newname","surname":"newsurname"}]
I think it would be easiest to store the data in a session, something like this:
<?php
session_start();
if (isset($_GET['name'])) {
$_SESSION['json'][] = $_GET;
}
echo json_encode($_SESSION['json']);
?>
Edit: You may want to filter the $_GET array before storing it in the session so that you don't store values that aren't meant to be stored.
Edit: Of course, if you want to save this data for more than one session you would need to use files or a database (or perhaps a cookie). It all depends on what you want to do with the information.
I'm doing a script that involves choosing a random string from an array and redirecting to it (using headers). I want it so that using a get variable and it will load the array with the same name as it. So, if the get variable is random, then it would load the array random and use that.
Does that make sense?
I'm using for a random avatar script, so that it will get a username then choose the array for that username, then select a random avatar URL.
PHP supports "variable variables", so you could do something like:
$arrayName = $_GET['username'];
$arr = $$arrayName;
So, if you had an array defined in your script:
$bill = array(1, 2);
and the value of $_GET['username'] is 'bill', then $bill would be copied to $arr by the above.
For more see this documentation
Something like this?
$avatars = array(
'alex' => array('avatar1.jpg', 'avatar2.jpg', 'avatar3.jpg'),
'bob' => array('avatar4.jpg', 'avatar5.jpg', 'avatar6.jpg'),
'crissa' => array('avatar7.jpg', 'avatar8.jpg', 'avatar9.jpg'),
);
$username = $_GET['username'];
if (isset($avatars[$username])) {
$avatar = $avatars[$username][mt_rand(0, count($avatars[$username]) - 1)];
header('Location: ' . $avatar);
}
I have PHP code that is used to add variables to a session:
<?php
session_start();
if(isset($_GET['name']))
{
$name = isset($_SESSION['name']) ? $_SESSION['name'] : array();
$name[] = $_GET['name'];
$_SESSION['name'] = $name;
}
if (isset($_POST['remove']))
{
unset($_SESSION['name']);
}
?>
<pre> <?php print_r($_SESSION); ?> </pre>
<form name="input" action="index.php?name=<?php echo $list ?>" method="post">
<input type="submit" name ="add"value="Add" />
</form>
<form name="input" action="index.php?name=<?php echo $list2 ?>" method="post">
<input type="submit" name="remove" value="Remove" />
</form>
I want to remove the variable that is shown in $list2 from the session array when the user chooses 'Remove'.
But when I unset, ALL the variables in the array are deleted.
How I can delete just one variable?
if (isset($_POST['remove'])) {
$key=array_search($_GET['name'],$_SESSION['name']);
if($key!==false)
unset($_SESSION['name'][$key]);
$_SESSION["name"] = array_values($_SESSION["name"]);
}
Since $_SESSION['name'] is an array, you need to find the array key that points at the name value you're interested in. The last line rearranges the index of the array for the next use.
To remove a specific variable from the session use:
session_unregister('variableName');
(see documentation) or
unset($_SESSION['variableName']);
NOTE:
session_unregister() has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
Is the $_SESSION['name'] variable an array? If you want to delete a specific key from within an array, you have to refer to that exact key in the unset() call, otherwise you delete the entire array, e.g.
$name = array(0 => 'a', 1 => 'b', 2 => 'c');
unset($name); // deletes the entire array
unset($name[1]); // deletes only the 'b' entry
Another minor problem with your snippet: You're mixing GET query parameters in with a POST form. Is there any reason why you can't do the forms with 'name' being passed in a hidden field? It's best to not mix get and post variables, especially if you use $_REQUEST elsewhere. You can run into all kinds of fun trying to figure out why $_GET['name'] isn't showing up the same as $_POST['name'], because the server's got a differnt EGPCS order set in the 'variables_order' .ini setting.
<form blah blah blah method="post">
<input type="hidden" name="name" value="<?= htmlspecialchars($list1) ?>" />
<input type="submit" name="add" value="Add />
</form>
And note the htmlspecialchars() call. If either $list1 or $list2 contain a double quote ("), it'll break your HTML
If you want to remove or unset all $_SESSION 's then try this
session_destroy();
If you want to remove specific $_SESSION['name'] then try this
session_unset('name');
Currently you are clearing the name array, you need to call the array then the index you want to unset within the array:
$ar[0]==2
$ar[1]==7
$ar[2]==9
unset ($ar[2])
Two ways of unsetting values within an array:
<?php
# remove by key:
function array_remove_key ()
{
$args = func_get_args();
return array_diff_key($args[0],array_flip(array_slice($args,1)));
}
# remove by value:
function array_remove_value ()
{
$args = func_get_args();
return array_diff($args[0],array_slice($args,1));
}
$fruit_inventory = array(
'apples' => 52,
'bananas' => 78,
'peaches' => 'out of season',
'pears' => 'out of season',
'oranges' => 'no longer sold',
'carrots' => 15,
'beets' => 15,
);
echo "<pre>Original Array:\n",
print_r($fruit_inventory,TRUE),
'</pre>';
# For example, beets and carrots are not fruits...
$fruit_inventory = array_remove_key($fruit_inventory,
"beets",
"carrots");
echo "<pre>Array after key removal:\n",
print_r($fruit_inventory,TRUE),
'</pre>';
# Let's also remove 'out of season' and 'no longer sold' fruit...
$fruit_inventory = array_remove_value($fruit_inventory,
"out of season",
"no longer sold");
echo "<pre>Array after value removal:\n",
print_r($fruit_inventory,TRUE),
'</pre>';
?>
So, unset has no effect to internal array counter!!!
http://us.php.net/unset
Try this one:
if(FALSE !== ($key = array_search($_GET['name'],$_SESSION['name'])))
{
unset($_SESSION['name'][$key]);
}
Simply use this method.
<?php
$_SESSION['foo'] = 'bar'; // set session
print $_SESSION['foo']; //print it
unset($_SESSION['foo']); //unset session
?>