Custom fields in array not posting when containing numbers - php

I have a PHP form where I need to search custom fields. If the custom field contains a number, it won't show as posted, however a string of letters will.
If I var_dump($_POST['customfield']) it displays the field, key and value. I attempted a foreach loop to count how many fields post. It returns 0 if I only post with numbers.
$postCustomFields = $_POST['customfield'];
foreach ($postCustomFields as $key => $cfield) {
if ($postCustomFields[$key][$cfield] != null) {
$customfields++;
}
}
Fields are named customfield[0]. Inside the brackets is the field ID. I just need a way to have the numeric value be usable and count in the customfields array.
var_dump($_POST['customfield']) output. The key is the field ID:
array(9) {
[3]=>
string(1) "5"
}
Thanks

You are confused with array reference. You have array with array [key => value], but you try to access data like array[key][value] and there are not exists.
In your case your $postCustomFields[$key] will contains your ID 5

Related

How Do I retrieve a string value JSON in PHP?

I have a returned string result from an API and it looks like this.. for the life of me, I cannot retried the WorkID value!
The returned string is a json string:
{"notes":"","RecordsStatus":"{\"0\":{\"WorkID\":\"0090210\",\"Message\":\"Record Created\"}}"}
It has two parts:
“notes” and “RecordStatus”.
If message is empty, means the batch is imported without error.
In RecordStatus, there are two parts too.
First is the index number of the record, and it has second part that the key for the record created(in my case it’s the WorkID) and a message tells the record is created or updated(in my case, it’s created).
Array
(
[notes] =>
[RecordsStatus] => {"0":{"WorkID":"0090210","Message":"Record Created"}}
)
Do a Var_dump() of decoded_json results in this:
array(2) {
["notes"]=>
string(0) ""
["RecordsStatus"]=>
string(52) "{"0":{"WorkID":"0090210","Message":"Record Created"}}"
}
I tried
foreach($decoded_json as $item) {
$uses = $item['RecordsStatus'][0]['WorkID']; //etc
}
but does not work

Problem with PHP array referenced by string index on Laravel application

I'm having a problem with an array in PHP. The thing is that want to display some users info in a table on my page, these users have several properties. I just want to display the username followed by 4 properties, this properties in my database are boolean type (true/false). In order to represent these values on the list I'm using checkboxes, so each checkbox displays checked or not checked according to the value on database. I've already got those values through a query. I'm just having issues on the displaying on my view (page).
In order to check if the property is true or false I'm using two foreach loop. I use the first one to pass for each user and the second one to evaluate the 4 properties of each user. I also preset an array that is responsible for storing if that property is true or false. So if the property is true the index "selected" on my array is going to be true.
The array structure is:
$choiceProperty['text'] // This already contains the four possible properties.
$choiceProperty['selected'] // This is going to store true if the property is true.
$choiceProperty['user_id'] // This is going to store the id of the user.
This is my code:
foreach ($user as $key => $userIndiv) {
foreach ($properties as &$choiceProperty) {
unset($choiceProperty['selected']);
if ($choiceProperty['text'] == 'A' && $userIndiv->CategoryA) {
$choiceProperty['selected'] = true;
}
if ($choiceProperty['text'] == 'B' && $userIndiv->CategoryB) {
$choiceProperty['selected'] = true;
}
if ($choiceProperty['text'] == 'C' && $userIndiv->CategoryC) {
$choiceProperty['selected'] = true;
}
if ($choiceProperty['text'] == 'D' && $userIndiv->CategoryD) {
$choiceProperty['selected'] = true;
}
$choiceProperty['user_id'] = $userIndiv->id;
}
array_push($finalChoices, $properties);
}
As you can see each $userIndiv->CategoryA, CategoryB, CategoryC... already contains the value obtained from the database.
At the end of each user I add the current $properties array to another array $finalChoices in order to check again for the next user and so on.
The problems comes when I printed the $finalChoices array to see its content and I see that it contains an array for each user with its properties but the last index of each array of each user contains the exact same value for all the arrays.
See what I mean:
First position of array:
Second position of array:
Third and last position of array:
As you can see all elements of arrays in their last position have the same values of the last position array. So they're not showing their real value. For example, based on my database the first and second arrays should have "selected" on its last position since they have 'true' in CategoryD.
I'm quite new in PHP and I'm not sure what I'm doing wrong. Of course it could be something missing on my logic that could be making me have this error. If you could help me I'd be grateful!
I also want to apologize for my English, I'm not native speaker and it's still improving. Thank you.
To finish I'd like to add a picture of how that looks on my view:
View

I need to remove all elements from an associative array based on a variable name

I am reading input from the user (in Laravel) and have rules associated to each of those inputs. If the user selects a checkbox (for that specific table), I would like to remove all the rules from the $rules associative array for that table.
To better illustrate, I have created two arrays mimicking the behaviour.
My input array is as follows:
$input = array("TB1_course" => ['0'=>'CHEM 1E03', '1'=>'ENG 1D04'
],
"TB1_section" => ['0'=>'CHEM 1E03', '1'=>'ENG 1D04'
],
"TB1_checkbox" => "1",
"TB2_course" => ['0'=>'CHEM 1E03', '1'=>'ENG 1D04'
],
"TB2_checkbox" => "0"
);
$rules= array(
'TB1_course.*' => 'required_with',
'TB1_section.*' =>'required_with',
'TB2_course.*' =>'required_with'
);
You can see from the input array that TB1_checkbox has a value of 1. If it has a value of 1, I would like to remove all the rules associated with TB1 (i.e. remove the elements in $rules with a key containing 'TB1').
I attempted to do as such, and was partially successful. My code looks like:
foreach ($input as $key=>$value){//go thru every element of the inputs
if ((strpos($key, 'checkbox')!==false) && $value==1){//if it contains 'checkbox'
//and checkbox is selected
$table_name= substr($key, 0,3);//name of table
//now go thru $rules and remove all elements which contain a word of $table_name
$rules=array_filter($rules, function($x){
return strpos($x, $table_name)!==0;//problem lies here
}, ARRAY_FILTER_USE_KEY);
}
}
However my code isn't working. The strpos() function is unable to read the $table_name variable, and leads to problems. If I manually pass in a string, it ends up working (i.e. 'TB1' instead of $table_name), but I have to have the flexibility of checking all my tables (so the rules containing 'TB2' have to be removed if "TB2_checkbox" has a value of 1). Is there any way to solve this issue?
Thank you for the help.

How to delete array element by index

Is there any possible way to delete element from array? It is shopping cart storing item IDs. I want to make delete function.
For example - cart_handler.php?delete=2687
array(5) { [1967]=> float(1) [1966]=> float(1) [2233]=> float(5) [2687]=> float(1) [2081]=> float(4) }
Yes you can, the easiest way would be to search for the item ID in the array, and then unset the key associated with it -- and then as an extension you could re-base the array to fix the array keys. Please Note: I haven't put any validation on the $arrayKey and what it returns, you should ensure that the array_search function is returning as expected before unsetting the array key just to be safe.
So something like this:
$data = [1967, 1966, 2233, 2687, 2081];
$arrayKey = array_search(1966, $data);
unset($data[$arrayKey]);
The specified product ID would be unset by that, just replace 1966 with your $_GET variable. i.e.
array_search($_GET['delete'], $data)
And the $data array would be a list of all your valid product IDs, that you could pull out from your database, or wherever you are storing them.
If you want to re-base the key indexes after this you can do:
$data = array_values($data);
What the above does is fixes the array key indexes, when you unset an element it will be removed from the array, but all keys will maintain their current indexes. So the array indexes may progress like so: 0, 1, 3, 4. If you re-base the array with the above they'll progress naturally again: 0, 1, 2, 3.
Hope that helps, any questions just let me know.

creating multiple php arrays

I have a html form with checkboxes. Someone selects one or more checkboxes and hit the delete button then it will delete the files references out of the database and delete the files out of Amazon S3. This is the code I used to find all the checkboxes
$checkbox_select = JRequest::getVar('checkboxselect', '', 'POST'); //just a Joomla way of doing a $_POST with extra security
var_dump($checkbox_select); //this returns: array(2) { ["video_1.mp4"]=> string(2) "on" ["video_2.mp4"]=> string(2) "on" ["video_3.mp4"]=> string(2) "on"}
// Localize and sanitize each individual value
foreach (array_keys($checkbox_select) as $element) {
$deleteNames[] = $db->quote($element);
}
var_dump($deleteNames); //array(3) { [0]=> string(13) "'video_3.mp4'" [1]=> string(13) "'video_2.mp4'" [2]=> string(13) "'video_1.mp4'" }
My problem is with Amazon S3 and multiple file deletion. The format I need to put S3 deletion in is quite confusing:
$s3->delete_objects('mybucket', array(
'objects' => array( // accepts a *list* of one or more *hashes*
// a *hash* that contains a "key" key with a value, and maybe a "version_id" key with a value
array('key' => 'object (file) name'),
// a second hash representing a file
// a third hash representing a file
// and so on...
),
));
As far as I understand (from S3 delete_objects function) the final associated array has key as the actual key value. With the last var_dump I've got all video names in an array now I just need to convert that array to a bunch of arrays in this format:
array ('key' => 'video_1.mp4'),
array ('key' => 'video_2.mp4'),
array ('key' => 'video_3.mp4'),
...and so on
How can I create these arrays? Should I be using the first var_dump I have or the second (they both have the video file names listed)? Thanks in advance.
You can use foreach to loop over your array and create a new array in the desired format.
Example:
<?php
foreach (array_keys($checkbox_select) as $element) {
$deleteNames[] = array('key' => $db->quote($element));
}
Untested, may contain errors
have a look at this post in the php documentation for array_push(). You'll get a brief idea of how to achieve it.

Categories