I have a function that I want to generate an array with. The format of the array is specific and only values need to be changed based on the arguments of my function. Here's the function:
function generatearray($name1, $field1, $name2, $field2) {
$language = ($user->language) ? $user->language : 'und';
$edit = array(
$name1 => array(
$language => array(
0 => array(
'value' => $field1,
),
),
), // ..... other elements $name2
);
return $edit;
}
$name2 and $field2 are optional arguments.
Not sure what the question is...but this code will do exactly what you're wanting to know about...a way to build an array based on up to 2 name/value pairs provided to a function.
printarray(generatearray('name_one','field_one','name_two','field_two'));
function generatearray($name1, $field1, $name2 = null, $field2 = null) {
$new_array = array();
$language = isset($user->language) ? $user->language : 'und';
$new_array[$name1][$language] = $field1;
if (!is_null($name2) && !is_null($field2)) {
$new_array[$name2][$language] = $field2;
}
return $new_array;
}
function printarray($arr) {
foreach ($arr as $user_key => $user_value) {
echo "User: ".$user_key."<br />";
foreach ($user_value as $language_key=>$language_value) {
echo "Language: ".$language_value."<br />";
}
}
}
Related
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
Here i added
"value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4"
using $str Dynamically with the help of for loop because it is dynamic not fixed.
I want to make this array like the below, so it can work and print correct output - It's my desired output(I want this array like this to be working)
array(
"data"=>array(
"userid"=>"$row->uid",
"value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4",
"acc_id"=>"$acc_id",
"tloop"=>"$timeloopc"
),
"next"=>"$next"
);
Output is -
But array taking the value of $str as string and when i print thisit shows output -
Array (
[data] => Array (
[user1] => 1
[0] => "value1"=>"$row->field1",
"value2"=>"$row->field2",
"value3"=>"$row->field3",
"value4"=>"$row->field4",
"value5"=>"$row->field5"
[user2] => 2
[fi] => 3
)
[next] => 4
)
The Above output is issue... Here array processing some key and value but not processing $str value... it's taking it as sting.
It's now processing the $str values as string from "value1" and "field1"..to..4
Help me to dynamically fill key and value in an associative array using for loop.
In the array "value1 and field1" - here numbers are dynamic - "value2" and "field2"...
When i am making array dynamic, it's not working like array. If i make it static it works fine.
So please help me to make $str value from string to array value(object)...
Here is complete code -
<?php
$ct = 4;
$str = '';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= '"value';
$cuntc = $cunt.'"';
$rw = '"$row';
$fild= "field";
$cp = $valu.$cuntc."=>".$rw."->".$fild.$cuntc;
$str .= $cp . ',';
}
//trim the , from last value
$str = rtrim($str, ",");
$main= array("data"=>array("userid"=>"1","$str","acc_id"=>"10","fi"=>"3"),"next"=>"4");
print_r($main);
?>
I don't know what exactly you want.
There is a code, which build array you'd like to have:
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$ct = 4;
$subArray = array();
$resultArray = array();
$resultArray['data']['userid'] = '$row->uid';
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= 'value';
$rw = 'row';
$fild= "field";
$resultArray['data'][$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt;
}
$resultArray['data']['acc_id'] = '$acc_id';
$resultArray['data']['tloop'] = '$timeloopc';
$resultArray['next'] = '$next';
echo "<pre>";
var_dump($resultArray);
echo "</pre>";
But if you don't need restricted key ordering, you can use something like this (it's rebuild $main array):
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$fields = array();
for($cunt=1; $cunt<=$ct; $cunt++)
{
$valu= 'value';
$rw = 'row';
$fild= "field";
$fields[$valu . $cunt] = '$' . $rw . '->' . $fild .$cunt;
}
foreach ($fields as $key => $value) {
$main['data'][$key] = $value;
}
And there is solution with functions:
function generateFieldArray($keyName, $obj, $field, $rowCount)
{
$resultArray = array();
for($count=1; $count<=$rowCount; $count++)
{
$resultArray[$keyName . $count] = '$' . $obj . '->' . $field .$count;
}
return $resultArray;
}
function buildMainArray($inputArray, $keyName, $obj, $field, $rowCount)
{
$arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount);
foreach ($arrayToAdd as $key => $value) {
$inputArray['data'][$key] = $value;
}
return $inputArray;
}
function buildMainArray2($inputArray, $keyName, $obj, $field, $rowCount)
{
$resultArray = array();
$resultArray['data']['userid'] = '$row->uid';
$arrayToAdd = generateFieldArray($keyName, $obj, $field, $rowCount);
foreach ($arrayToAdd as $key => $value) {
$resultArray['data'][$key] = $value;
}
$resultArray['data']['acc_id'] = '$acc_id';
$resultArray['data']['tloop'] = '$timeloopc';
$resultArray['next'] = '$next';
return $resultArray;
}
$main= array(
"data"=>array(
"userid"=>"1",
"$str",
"acc_id"=>"10",
"fi"=>"3"
),
"next"=>"4"
);
$result = buildMainArray($main, 'value', 'row', 'field', 4);
// or
$result = buildMainArray2($main, 'value', 'row', 'field', 4);
I'm using Laravel for an API and trying to fetch multiple _GET variables a user would type.
The code looks like this when all filters are used:
public function MUIntervalAPICall(Request $dte)
{
$date = $dte->dte;
$element_language = $dte->language;
$element_customer = $dte->customer;
$element_contract = $dte->contract;
$element_subcontract = $dte->subcontract;
$element = $dte->element;
//all filters
if(isset($_GET['customer']) && isset($_GET['language']) && isset($_GET['contract']) && isset($_GET['subcontract']) && isset($_GET['element']))
{
$where = ['dte' => $date, 'element_language' => $element_language, 'element_customer' => $element_customer, 'element_contract' => $element_contract, 'element_subcontract' => $element_subcontract, 'element' => $element];
}
$mu_interval = MUInterval::select('element_customer', 'element_contract', 'element_subcontract', 'element_language', 'element_site', 'element', 'src_id', 'src_type_id', 'dte', 'intvl', 'val_src_id', 'exception_name', 'duration_seconds', 'duration_fte')
->where($where)
->get()->toArray();
function array_to_xml( $data, &$xml_data ) {
foreach( $data as $key => $value ) {
if( is_array($value) ) {
$key = 'Exception';
$subnode = $xml_data->addChild($key);
array_to_xml($value, $subnode);
} else {
$xml_data->addChild("$key",htmlspecialchars("$value"));
}
}
}
$xml_data = new SimpleXMLElement('<?xml version="1.0"?><muExceptions></muExceptions>');
array_to_xml($mu_interval,$xml_data);
$result = $xml_data->asXML();
return Response::make($result, '200')->header('Content-Type', 'text/xml');
}
Now a user would want to filter it out only with few variables in place. e.g. date and customer, or language and contract only.
I'm currently writing a long block of if-else statements to produce results (really long, to include all possibilities for six $_GET variables):
elseif(isset($_GET['subcontract']) && isset($_GET['element']))
{
$where = ['dte' => $date, 'element' => $element, 'element_subcontract' => $element_subcontract];
}
Is there a shorter method for such a long if-else statements?
Yes, you should learn about how Laravel validation and form request validation work:
https://laravel.com/docs/5.1/validation
https://laravel.com/docs/5.1/validation#form-request-validation
It's much shorter and more convenient way to do validation.
isset accepts multiple arguments at once:
if (isset($_GET['customer'], $_GET['language'], $_GET['contract'], ...))
You can use array intersections/diffs:
if (!array_key_diff(array_flip(['customer', 'language', ...]), $_GET))
If array_key_diff returns an empty array, all those keys exist in the $_GET array.
Write your conditions as below:-
if(isset($_GET['subcontract'],$_GET['element']) && !isset($_GET['customer'], $_GET['language'], $_GET['contract'])){
$where = ['dte' => $date, 'element' => $element, 'element_subcontract' => $element_subcontract];
}
elseif(isset($_GET['customer'], $_GET['language'], $_GET['contract'], $_GET['subcontract'],$_GET['element'])){
$where = ['dte' => $date, 'element_language' => $element_language, 'element_customer' => $element_customer, 'element_contract' => $element_contract, 'element_subcontract' => $element_subcontract, 'element' => $element];
}
Suggestion:- You should use Laravel's Validator Class for validations.
Refer below links.
http://www.sitepoint.com/data-validation-laravel-right-way/
https://laravel.com/docs/5.1/validation
Hello I wanna check if is string element of codeIgniter query, so I wanna compere to arrays.
I use this soulution but i get false in both case.
$data = array(
'Firstname' => $ime ,
'Lastname' => $prezime,
'Nick' => $username,
'EmailAddress' => $email,
'Uid' => $uid,
);
$rs = $this->db->query("Select Nick FROM cms_cart_customers");
$array = $rs->result_array();
if(!in_array($data['Nick'],$array))
{
$this->db->insert('cms_cart_customers', $data);
}
The result_array() function returns you a multi-dimensional array, even with a single column. You need to flatten the array in order to search the array linearly, try something like this:
$array = $rs->result_array();
$flattened = array();
foreach($array as $a) {
$flattened[] = $a['Nick'];
}
if(!in_array($data['Nick'],$flattened)) {
$this->db->insert('cms_cart_customers', $data);
}
Codeigniter query will return result in associative array and in_array() function will not going to do the trick.
Here is one way you can do this custom is_in_array function source
//Helper function
function is_in_array($array, $key, $key_value){
$within_array = false;
foreach( $array as $k=>$v ){
if( is_array($v) ){
$within_array = is_in_array($v, $key, $key_value);
if( $within_array == true ){
break;
}
} else {
if( $v == $key_value && $k == $key ){
$within_array = true;
break;
}
}
}
return $within_array;
}
$array = $rs->result_array();
if(!is_in_array($array, 'Nick', $data['Nick']))
{
$this->db->insert('cms_cart_customers', $data);
}
Other Method
If you are trying to avoid duplicate entry, you should use a Select query first to check that the 'Nick' = $username is already present in table, if not then Issue an insert
Example
$rs = $this->db->get_where('cms_cart_customers', array('Nick' => $username));
//After that just check the row count it should return 0
if($rs->num_rows() == 0) {
$this->db->insert('cms_cart_customers', $data);
}
I was create a shortcode which automatically generate shortcodes with given array key and value. Function names does not generate dynamically.
Note: Array KEY = ShortcodeName and Value = Wordpress Option field.
add_shortcode("auto_gen", "auto_gen");
function auto_gen() {
$a = array(
"get_address" => "mg_admin_address",
"get_phone" => "mg_admin_phone",
"get_fax" => "mg_admin_fax",
"get_email" => "mg_admin_email",
"get_hrs_mon" => "mg_work_hrs_mon_frd",
"get_hrs_sat" => "mg_work_hrs_sat"
);
foreach ($a as $k => $v) {
if(has_shortcode($k)) {
echo "<br>Found: ". $k;
} else {
add_shortcode($k, $k. "_init");
function $k. "_init"() {
return get_option[$v, ''];
}
}
add_shortcode();
echo $k ." -> ". $v. "<br />";
}
}
There is any possible way to do this.
NOTE:
Here, get_address array key is a shortcode. And it is dynamically generate when It pass though loop. get_address is changable. If I change get_address with get_user_address then get_user_address generate generated. "get_address", "get_phone" are CHANGABLE at END LEVEL.
Developer also generate shortcodes to access created wp_options useing get_options, simply pushing elements in array. e.g. "shortcode_name" => "option_name"
The function add_shortcode has a third parameter that contains the current shortcode, so the same callback can be used multiple times:
$all = array( 'address', 'phone', 'fax', 'email', 'hrs_mon', 'hrs_sat' );
foreach ( $all as $s )
add_shortcode( "get_$s", 'general_shortcode' );
function general_shortcode( $atts, $content = '', $shortcode = '' )
{
switch( $shortcode )
{
case 'get_address':
$return = 'ADDRESS';
break;
case 'get_phone':
$return = 'PHONE';
break;
default:
$return = 'OTHER SHORTCODES';
break;
}
return $return;
}
Another possibility:
Class AllShortcodes{
private $all = array(
"get_address" => "mg_admin_address",
"get_phone" => "mg_admin_phone",
"get_fax" => "mg_admin_fax",
"get_email" => "mg_admin_email",
"get_hrs_mon" => "mg_work_hrs_mon_frd",
"get_hrs_sat" => "mg_work_hrs_sat"
);
public function __construct() {
foreach ( $this->all as $key => $value )
add_shortcode( $key, array( $this, 'general_shortcode' ) );
}
public function general_shortcode( $atts, $content = '', $shortcode = '' )
{
return $this->all[$shortcode];
}
}
$myShortcodes = new AllShortcodes;
Try following code:
add_shortcode("auto_gen", "auto_gen");
function auto_gen() {
$a = array(
"get_address" => "mg_admin_address",
"get_phone" => "mg_admin_phone",
"get_fax" => "mg_admin_fax",
"get_email" => "mg_admin_email",
"get_hrs_mon" => "mg_work_hrs_mon_frd",
"get_hrs_sat" => "mg_work_hrs_sat"
);
foreach ($a as $k => $v) {
if(has_shortcode($v,$k)) {
echo "<br>Found: ". $k;
} else {
add_shortcode($k, $k."_init");
$func =$k."_init";
$func($v);
}
echo $k ." -> ". $v. "<br />";
}
}
function get_address_init ($v) {
return get_option($v, '');
}
function get_phone_init ($v) {
return get_option($v, '');
}
function get_fax_init ($v) {
return get_option($v, '');
}
function get_email_init ($v) {
return get_option($v, '');
}
function get_hrs_mon_init ($v) {
return get_option($v, '');
}
function get_hrs_sat_init ($v) {
return get_option($v, '');
}
I am trying to make first array value to uppercase.
Code:
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
So before save($data, $id) to database I want to convert position value to uppercase. I have tried by this
$data['position'] = strtoupper($data['position']);
but than it is not storing the value in db with uppercase but as it is what user inputs.
Current output of $data:
Array ( [position] => it [label] => Information Technology )
And I want it in uppercase as IT
Added Model Method
public function get_positions_array($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
$positions = parent::get($id, $single);
$array = array();
foreach($positions as $pos){
$array[] = get_object_vars($pos);
}
return $array;
}
Main MY_Model method
public function array_from_post($fields)
{
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
This should work:
$data = $this->positions_model->array_from_post(array('position', 'label'));
$data['position'] = strtoupper($data['position']);
$this->positions_model->save($data, $id);
If Its not, then $data array have only read attribute.
The array_from_post() method returns an array with the format below:
$data = array(
'position' => 'it',
'label' => 'Information Technology'
);
So, you could make first value of the array to uppercase, by using array_map or array_walk functions as follows:
$data = array_map(function($a) {
static $i = 0;
if ($i === 0) { $i++; return strtoupper($a); }
else return $a;
}, $array);
Note: This only works on PHP 5.3+, for previous versions, use the function name instead.
Here is the array_walk example, which modifies the $data:
array_walk($data, function(&$value, $key) {
static $i = 0;
if ($i == 0) { $i++; $value = strtoupper($value); }
});
Again, if you're using PHP 5.2.x or lower, you could pass the function name instead.