How to assign an element to a PHP associative array?
For example, I attempt this but not working.
$testSCSI = array('test' => <input type="checkbox"> Test Results</input>);
echo json_encode($testSCSI);
When reading the json from my jquery code, it only gives me value of "Test Results" and not the checkbox.
Is this what you mean? Did you forget the quotes?
$testSCSI = array('test' => '<input type="checkbox"> Test Results</input>');
The problem is likely in your jQuery code, not the PHP.
The PHP should be outputting this:
{"test":"<input type=\"checkbox\"> Test Results</input>"}
And then in jQuery you want to make sure you're using html() rather than text() to assign it.
That really isn't how arrays work, you don't store HTML elements in them you store data elements. An example associative array might look something like:
$a = array("test1"=>"value1", "test2"=>"value2");
You could accomplish what you are trying to do by using properly quoted strings for your HTML elements. You could also use single quotes so you don't have to escape the quotes in type parameter.
$a = array("test"=>"<input type=\"checkbox\" />Test Results\n");
HTH.
Related
Look I have a form like this:
<form method="post">
<input name="variable[var1][var2]" value="44"/>
</form>
I want to get the value of variable[var1][var2] in PHP using a string like:
$str = "['variable']['var1']['var2']";
echo "{$_POST{$str}}";
Why I need to do that?
I need it because the code that gets the value is totally dynamic and I cannot get or set manually the value using $_POST['variable']['var1']['var2'].
Can you help?
NOTE: I know this is possible to get it using $_POST['variable']['var1']['var2'], please don't ask me about why I'm not using this way. Simply I need to use as above (using $str).
You can use preg_match_all() to get all the indexes in the string into an array:
$indexes = preg_match_all('/(?<=\[\')(?:[^\']*)(?=\'\])/', $str);
$indexes = $indexes[0]; // Get just the whole matches
Then use a loop to drill into $_POST.
$cur = $_POST;
foreach ($indexes as $index) {
$cur = $cur[$index];
}
At this point $cur will contain the value you want.
You're WAY overthinking it. Anything you put in [] array notation in a form field's name will just become an array key. The following is LITERALLY all you need:
<input name="foo[bar][baz][qux]" ... />
$val = $_POST['foo']['bar']['baz']['qux'];
You cannot use a string as an "address" into the array, not without insanely ugly hacks like eval, or parsing the string and doing a loop to dig into the array.
It's hard to believe that this is a requirement. If you could expand more on what you're trying to achieve, someone undoubtedly has a better solution. However, I will ignore the eval = evil haters.
To echo:
eval("echo \$_POST$str;");
To assign to a variable:
eval("\$result = \$_POST$str;");
If you're open to another syntax then check How to write getter/setter to access multi-level array by key names?
So I am working with PHP to pass a PHP array over a jQuery Ajax request to another PHP page. This is quite the task. For some reason, my json_encode is returning an array instead of a string, I am not quite sure why. Here is my PHP code:
$new_spreadsheet = nl2br($_POST['spreadsheet']);
$new_spreadsheet = explode('<br />', $new_spreadsheet);
array_shift($new_spreadsheet);
$new_spreadsheet = array_values($new_spreadsheet);
echo json_encode($new_spreadsheet);
I would show you the output, but it is really long. Basically this is outputting a PHP array which consists of each row on the spreadsheet. This is what I want to have, but the problem is that I don't want the quotes and everything in the array. I am pretty sure I need to run json_decode, but when I do that my code returns an error saying that the parameter needs to be a string. I can tell something is not right, but am not quite sure what I need to change. I would appreciate any advice.
Update: At this point, when I try to loop through the array and print each value, the first array index is equal to a double quote like so: ". There are double quotes in random values throughout the area. I am not quite sure about what is causing this.
If I echo the rows from within the json_encoded PHP array onto the console, I get the following output:
"
correct value
correct value
correct value
"
You're using JSON, which means you have to adhere to somewhat more stringent syntax rules than Javascript's. e.g.
<?php
$arr = array('This' => 'is', 'an' => 'array in php');
echo json_encode($array);
?>
output:
{"This":"is","an":"array in PHP"}
There is NO way to avoid getting quotes on the values, as they're a fundamental requirement of JSON (and Javascript). If you don't want quotes, then don't use JSON.
try only br.
$new_spreadsheet = explode("<br>", $new_spreadsheet);
It will work. and json_enode can never return an array. try var_dump and check.Also make sure before you post, use htmlspecialcharacters.
I have an associative array that is built dynamically from a MySQL table like so:
array(['p.id'] => 3, ['p.fname'] => 'Bill', ['p.lname'] => 'O\'Reilly')
This is a large array and was built this way for reasons that are too long to go into here. The problem, as you can see is that when we attempt to access the value of ['p.lname'] we get "O\"
Anyone have any ideas on how to get around this without modifying the way the array is built? I am currently stripping the slashes and internal apostrophes as a work around, but would prefer to leave the apostrophes in place and just strip the slashes.
This is complicated by the fact that the output goes into a form input like so:
$field = "<input type='text' name='$input_unique_id' style='width:$width;' value='$array_value' />";
strip slashes
That's right so far.
This is complicated by the fact that the output goes into a form input
And this is a different issue: You use single quotes for the HTML element attributes, so you cannot use them in the attribute value like that*. Attribute values always should be escaped with htmlspecialchars (you will have to set the ENT_QUOTES flag in this case)
*) your current HTML (with stripslashes applied) looks like this:
<input value='O'Reilly'>
The Reilly' part is invalid and thus ignored, this leaves value='O'
You need to loop through each element of the array and strip the slashes as such:
foreach ($arr as $key => $value) {
$arr[$key] = stripslashes($value);
}
Basically, I have working solution for this, but I'm wondering if it could (should?) be done better in some other way.
I have table I'm creating in PHP with values from MYSQL. Each item in table has multiple values. In each line there is single link and clicking on this link fires up jQuery function. In each link there is also VALUE attribute with values from multiple MYSQL fields and joined with &&:
PHP code is:
foreach ($this->_data as $l)
{
?>
...
<td>Link</td>
...
<?php
}
And jQuery function to fire up when clickin' on link is:
$(".clickMe").click(function() {
myData = $(this).attr('value').split('&&');
});
Script splits string in VALUE attribute on && and creates an array myData with values:
myData[0] => value passed from $l->_data1 in PHP
myData[1] => value passed from $l->_data2 in PHP
Is this the right way to do it?
It's fine, as long as you'll never have && in your data. You could use json_encode() in PHP and then decode this into an array in JavaScript. That would be a more standard solution.
I would recommend against using && which looks like a boolean AND. Instead I would probably use something like a pipe to separate them val1|val2.
I think you're better off passing the whole joined string in to PHP and splitting it out there. It saves you work on both ends having to put the two resultant values into the proper post or get variables to send to PHP.
Then on the PHP side, it's a little easier to validate the one value's format before splitting it, as you can use a single regex like:
// Validate both values at once: 1 or more digits, a pipe, and one or more digits
if (preg_match('/^(\d+)\|(\d+)$/', $_POST['jqueryinput'])) {
// explode() and use in PHP...
list($val1, $val2) = explode("|", $_POST['jqueryinput']);
}
i'm not sure how to explain it correctly, but i would like to use $_POST values like this $_POST[0] and not like this $_POST['form_field_name'].
Let's say i have 3 form fields so if i'd like to get data from post like this:
echo $_POST[0];
echo $_POST[1];
echo $_POST[2];
I hope you guys understand what i wanna do here.
Try it like this:
$values = array_values($_POST);
No idea why you would do such a thing though.
I would not recommend ever to refer to your $_POST values with indexes, as it is generally a bad idea.
You can access them by indexes if you do this:
$items = array_values($_POST);
$foo = $items[0];
$bar = $items[1]
You can also run through your values with a foreach loop, like this (which is better, but still bad!)
foreach($_POST as $item)
{
// do your thing here
}
$_POSTs variables depends on the name attribute of the form element as you can read in this link.
On the other hand the attribute name of the form elements according to W3C always must begin with a letter.
But I think you can prepare the $_POST variable before all your code (at the begining of your php script) with:
$arrPostVariables = array_values($_POST);
And then call them in the way as you want, but I think you will previously must detect the order of the array in order to avoid errors by not having the text of each variable.
This should work:
<input name="0" value="val0" />
<input name="1" value="val1" />