Add mutiple values to one column - php

We are working on a website based on SilverStripe and this site is connected with a SugarCRM database.
We have created a Form with a CheckboxSet with multiple values and store it a variable called $data['Interessen']
$set_entry_parameters = array(
"session" => $session_id,
"module_name" => "Contacts",
"name_value_list" => array(
array(
"name" => "interessen_c",
"value" => $data['Interessen']['fotografie']
),
array(
"name" => "interessen_c",
"value" => $data['Interessen']['dance']
)
)
);
Now the last array with "interessen_c" overwrites the previous values. We want to add more than one value at one time.
How is this possible?

If the contents of $data['Interessen'] can only have values from a fixed list of possibilities, I'd recommend making the field interessen_c into type multienum ("Multi-Selection Dropdown" field).
For that field create a list of all available items in Sugar (e.g. in Studio or creating the app_list_strings entry manually via code).
Sugar will then support multiple values in this field and display them nicely.
If your program writes the data by communicating with the Sugar REST API you can then just pass the $data['Interessen'] array as the value for interessen_c and Sugar will know what to do with it.
If your program writes the data directly to the interessen_c field in the database, then the field contents must adhere to the following format:
^value1^,^value2^,^value3^
So with ^ around each value and all items being separated by ,
Here an example of how to convert the array values to such a string in PHP:
$interessen = array();
foreach ($data['Interessen'] as $value) {
// add value surrounded by ^ to array
$interessen[] = "^$value^";
}
// transform values in array to string with items being separated by ,
$interessen = implode(',', $interessen);
Side-Note:
From within Sugar one can use encodeMultienumValue($arr) and unencodeMultienum($string) to convert from array to db-string format and back.
Both functions are defined in include/utils.php

Related

A csv file has a state, county, and data on each line. How can I use PHP associative arrays to convert to states=>counties=>county=>data

My data looks like:
countyFIPS,County Name,State,stateFIPS,1/22/20,1/23/20,1/24/20,1/25/20,....
1001,Autauga County,AL,1,0,0,0,0,0,0,0,0,....
...
I've been able to retrieve it using an Ajax call and collect it into a simple PHP array, then convert it to json to use in my javascript application. While it appears that the data is all counties of a state, followed by the same configuration for the next state, there is no guarantee that it won't be mixed up in some later set of data.
I'm an old Fortran programmer, and would tend to build a hash table for the "states", then check if the state exists in the hash table. If not create a new hash table and add this empty hash table as the value for the key with the name of the state to the "state" hash table. Then check the state hash table to see if it has a key for the county. Again, if it doesn't, then add an empty array as the value for the key with the county name and add that to the state hash table, then proceed to put the values for that row into the county array. I know this will work, but thought maybe there was some clever way to use associative arrays in PHP to accomplish the same thing.
I look at array_filter, but can't seem to figure out how to adapt it to this case. Are there other functions that might work here?
Then, once I have this structure of
$nested_object = { state1=>{county1,county2,county3...},state2=>{counties}},
and those counties have:
county=>[values],
how can I easily convert this to a json structure? Should it have other keys like "states", and within a state "counties". From looking at Haroldo's question "Convert a PHP object to an associative array" of Dec 3, 2010, it appears like I would use:
$array = json_decode(json_encode($nested_object), true);
Will this give me the structure I am looking for?
I want to end up with a structure that I can ask for the states as a set of keys, then for a selected state ask for the counties in that state as a set of keys, and upon selecting one, get the array of values for that state/county. This has to run on a server with potentially a large amount of data and a moderate amount of hits per unit time so I wanted as reasonably efficient way as possible.
I want to end up with a structure that I can ask for the states as a set of keys, then for a selected state ask for the counties in that state as a set of keys, and upon selecting one, get the array of values for that state/county
Okay, so you need something like:
$structure = [
'AL' => [
'counties' => [
'FIPS1' => 'County1',
'FIPS2' => 'County2',
],
'data' => [
'FIPS1' => [
[ 'date1' => value1, 'date2' => value2, 'date3' => value3... ]
],
],
],
'AK' => [ ... ]
];
You can do that using array_map() and a lambda function writing to $structure, but... in my experience, it is not worth it.
Best to do like you said:
while ($row = get_another_row()) {
$countyFIPS = array_unshift($row);
$countyName = array_unshift($row);
$stateName = array_unshift($row);
$stateFIPS = array_unshift($row);
if (!array_key_exists($stateName, $structure)) {
$structure[$stateName] = [
'counties' => [ ],
'data' => [ ],
];
}
if (!array_key_exists($countyFIPS, $structure[$stateName]['counties'])) {
$structure[$stateName]['counties'][$countyFIPS] = $countyName;
$structure[$stateName]['data'][$countyFIPS] = [ ];
}
// Now here you will have $headers, obtained from the header row unshifting
// the first four fields.
foreach ($headers as $i => $key) {
$structure[$stateName]['data'][$countyFIPS][$key] = $row[$i];
}
}
This way if you add two CSVs with different dates, the code will still work properly. Dates will not be sorted though, but you can do that with a nested array_map and the aksort function.
To output this in JSON, just use json_encode on $structure.

CakePHP 2: Using stored array as keys in a $this->Model->find statement

I have a dropdown on my site that allows for multiple selections:
$this->Form->input('systems', array('label'=>'System Assignments', 'empty'=>'', 'default'=>'', 'div'=>false, 'multiple'=>true, 'class'=>'chosen',
'options'=>$systems));
This code from my controller populates the $systems variable:
$systems = $this->Discrepancy->find('list', array('fields' => array('id', 'description'),
'conditions'=>array('Discrepancy.deleted_record' => 0),
'order'=>array('Discrepancy.display_order'=>'ASC')));
$this->set(compact('systems'));
When the user makes their selection(s), the row ID's are stored as an array in a table called Users in a field called systems.
$system_string = implode(',', $this->request->data['User']['systems']);
$this->request->data['User']['systems'] = $system_string;
systems
-------
50,22
On my Edit screen, I would like to be able to use that array of values as my list of ID's for retrieving and displaying the user's system choices, by adding a 'value' parameter to the dropdown.
'value'=>array_key($chosen_systems);
How can I use these stored values in a $this->Model->find statement?
Got it. Guess I needed to write it all out first.
Put the following line in the $this->Model->find statement:
'conditions'=>array('Discrepancy.id'=>explode(',',$var_for_systems_from_db))

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.

Programatically extending an array with sub arrays

I have a working array as follows
"content" => array
(
array //sub array for image 1
(
'url' => $uploadspath.$media_url0,//main image
"type" =>$type0,//media type
"caption"=>$caption0
),
array //sub array for image 2
(
'url' => $uploadspath.$media_url1,//main image
"type" =>$type1,//media type
"caption"=>$caption1
),
array //sub array for image 3
(
'url' => $uploadspath.$media_url2,//main image
"type" =>$type2,//media type
"caption"=>$caption2
),
....Programatically add new sub arrays here subject to the existence of $media_url(4,5,6 etc)..
);
I am getting the $media_url and other data from database. I would like too programatically extend the array by adding additional sub arrays and associated URL/type/caption elements IF there is a value for $media_url4; $media_url5; $media_url6; $media_url7; etc. etc. (Max 10 images)
My problem is how to code the extension of my array with additional sub-arrays based purely on the existence of additional media_urls. Simplistically I would like to be able to do something along the following lines but I don't know how to implement it within a nested array structure...
if ($media_url4) {code to add sub array/element for image 4}
if ($media_url5) {code to add sub array/elementsfor image 5}
etc...
Thank you for any assistance.
//Below we have a function or pdo function that return the new values from database that you want to put in the CONTENT MASTER ARRAY, NOW we put the values in a variable $rows
$rows = functionThatReturnNewValuesToPutInContentArray();
//The foreach looping the variable rows, getting each row in database and putting this in a variable $row
foreach($rows as $row){
//If the $row object data from database contains media_url value add new subarray to masterContentArray
if($row->media_url != ''){
$newSubArray = [
//$row->media_url, is considering that you have a column in your db named by media_url, and that contains url string
'url'=>$row->uploadsPath . $row->media_url,
'type'=>$row->type,
'caption'=>$row->caption,
];
array_push($masterContentArray['content'], $newSubArray);
}
}
return json_encode($content);

How do you populate a dropdown box using data from another model so that all rows are taken as options in yii?

I'm using version 1.1.14 of yii.
My VIEW file has
<?php echo $form->dropDownList($model,'estado', CHtml::listData(Estado::model()->findAll(), 'id', 'estado')); ?>
I have a model called Estado which was generated from a table with only 2 fields ID as PK and estado where I have my data. Which has 3 rows Active, Inactive, Prospecting.
So far the code only shows the last row of that table, ignoring the first 2.
What am I doing wrong?
for the dropdown list you can pass a normal array :
$data = array(
'number1',
'number2',
'number3',
);
or an array with key => value
$data = array(
7 => 'number7',
2 =>'number2',
4 =>'number4',
);
Chtml::listData() will only help you make that array avalable for the function
however if you need to make a combination of models ( or arrays) you have to do that manually using array concatenation functions such as CMap::mergeArray()

Categories