I'm trying to escape values from a multidimensional array for my database class. The code I have currently:
// Function to escape array values
private function esc_sql_arr(array $to_esc) {
$clean_arr = array();
foreach($to_esc as $k => $v) {
if(is_array($to_esc[$k])) {
foreach($to_esc[$k] as $key => $val) {
$k = $this->_mysqli->real_escape_string($k);
$key = $this->_mysqli->real_escape_string($key);
$val = $this->_mysqli->real_escape_string($val);
$clean_arr[$k][$key] = $val;
}
} else {
$k = $this->_mysqli->real_escape_string($k);
$v = $this->_mysqli->real_escape_string($v);
$clean_arr[$k] = $v;
}
}
return $clean_arr;
}
I'm assuming the following input example (it should be 'where', I purposely changed it to test the above method):
$args = array(
"table" => "t'1",
"data" => array(
"c'sf4;(" => 'xdfbxdrf',
'c2' => "'t'est'",
'cs' => 'hey'
),
"whe're" => array(
'test' => 'test1'
)
);
var_dump:
array (size=3)
'table' => string 't\'1' (length=4)
'data' =>
array (size=3)
'c\'sf4;(' => string 'xdfbxdrf' (length=8)
'c2' => string '\'t\'est\'' (length=10)
'cs' => string 'hey' (length=3)
'whe\'re' =>
array (size=1)
'test' => string 'test1' (length=5)
The code works without any issue. However, is this the right way to escape a multidimensional array?
I believe I might not have to use this method since I use prepared statements. Any feedback on using this is welcome.
Related
I am trying to create and array to fill for my form_dropdown() for my view:
<?php echo form_dropdown('vendor', $vendors, '', 'class="form-control"') ?>
However, I am only getting the last value based on the function that generates the array:
public function get_vendors() {
$vendors = $this->db->table('vendor')->get()->getResultArray();
// Return key => value pair array
$array = array(
0 => 'Not Assigned'
);
if (!empty($vendors)) {
foreach ($vendors as $vendor) {
$array = array(
$vendor['id'] => $vendor['vendor']
);
}
}
return $array;
}
This function is within my model. The only problem I have is that it's returning only the last row from the table. However when I do a var_dump() for the $vendors I get all the rows. Not sure what I am doing wrong.
array (size=2)
0 =>
array (size=4)
'id' => string '1' (length=1)
'vendor' => string 'Blue Chip' (length=9)
'datecreated' => string '2022-08-16' (length=10)
'datemodified' => string '2022-08-16' (length=10)
1 =>
array (size=4)
'id' => string '2' (length=1)
'vendor' => string 'ASP' (length=3)
'datecreated' => string '2022-08-30' (length=10)
'datemodified' => string '2022-08-31' (length=10)
Changing the query to from getResultArray() to getResultObject() did the trick. So I was able to use $array[$vendor->id] = $vendor->vendor;
public function get_vendors() {
$vendors = $this->db->table('vendor')->get()->getResultObject();
// Return key => value pair array
$array = array(
0 => 'Not Assigned'
);
if (!empty($vendors)) {
foreach ($vendors as $vendor) {
$array[$vendor->id] = $vendor->vendor;
}
}
return $array;
}
If you still want to use getResultArray():
public function get_vendors() {
$vendors = $this->db->table('vendor')->get()->getResultArray();
// Return key => value pair array
$array = array(
0 => 'Not Assigned'
);
if (!empty($vendors)) {
foreach ($vendors as $vendor) {
$array[$vendor['id']] => $vendor['vendor'];
}
}
return $array;
}
I have tried a number of PHP functions like array_unique to merge the arrays I have but that does not work since these are not strings.
The starting output would be this on var_dump( $country_cities );
array (size=3)
0 =>
array (size=1)
'BH' =>
array (size=4)
'post_id' => int 7886
'country' => string 'BH' (length=2)
'city_name_eng' => string 'Laurence' (length=8)
'city_name_arabic' => string '3684hdfpfwbhisf' (length=15)
1 =>
array (size=1)
'BH' =>
array (size=4)
'post_id' => int 7885
'country' => string 'BH' (length=2)
'city_name_eng' => string 'Bahrain City' (length=12)
'city_name_arabic' => string 'vgdg824762' (length=10)
2 =>
array (size=2)
'BH' =>
array (size=4)
'post_id' => int 7885
'country' => string 'BH' (length=2)
'city_name_eng' => string 'Bahrain City' (length=12)
'city_name_arabic' => string 'vgdg824762' (length=10)
'KW' =>
array (size=4)
'post_id' => int 7841
'country' => string 'KW' (length=2)
'city_name_eng' => string 'Kuwait City' (length=11)
'city_name_arabic' => string ' مدينة الكويت' (length=24)
The Code below merges the different arrays above.
<?php
// Make the cities unique. Remove duplicates form the inner array.
$uniques = [];
foreach($country_cities as $arr ) {
foreach( $arr as $v) {
if( !in_array($v, $uniques, false) ) {
$uniques[$v['country']] = $v;
}
}
}
var_dump($uniques);
Results logged show the code cuts out some of the arrays.
/Users/..... on line php:74:
array (size=2)
'BH' =>
array (size=4)
'post_id' => int 7885
'country' => string 'BH' (length=2)
'city_name_eng' => string 'Bahrain City' (length=12)
'city_name_arabic' => string 'vgdg824762' (length=10)
'KW' =>
array (size=4)
'post_id' => int 7841
'country' => string 'KW' (length=2)
'city_name_eng' => string 'Kuwait City' (length=11)
'city_name_arabic' => string ' مدينة الكويت' (length=24)
Please help figure out my error or suggest a better way to fix it.
If I understood you correctly, this should be the result you wanted to achieve.
Each country code will be included once, while the cities (based on post_id) will only be added once.
<?php
$result = [];
$processedIds = [];
foreach ($country_cities as $ccs) {
foreach ($ccs as $cc => $details) {
// If the country has not yet been added to
// the result we create an outer array.
if (!key_exists($cc, $result)) {
$result[$cc] = [];
}
$postId = $details['post_id'];
if (!in_array($postId, $processedIds)) {
// Add the unique city to country's collection
$result[$cc][] = $details;
// Keep track of the post_id key.
$processedIds[] = $postId;
}
}
}
print_r($result);
<?php
//...
$uniques = [];
foreach($country_cities as $data ) {
foreach( $data as $countryCode => $item) {
if( !array_key_exists($countryCode, $uniques) ) {
$uniques[$countryCode] = []; //Create an empty array
}
$targetArray = &$uniques[$countryCode];
if( !array_key_exists($item['post_id'], $targetArray) ) {
$targetArray[$item['post_id']] = $item; //Create an empty array
}
}
}
Maybe this code will help?
I am trying to migrate user data from a Drupal database to Wordpress. I'm trying to parse through a data column from Drupal and reorganize it so I can import it where I need to in the Wordpress database. The data column in Drupal is a serialized string:
a:12:{s:23:"profile_membership_type";s:4:"Full";s:21:"ms_membership_add_new";s:0:"";s:18:"ms_membership_mpid";s:0:"";s:25:"ms_membership_amount_paid";s:0:"";s:32:"ms_membership_transaction_number";s:0:"";s:30:"ms_membership_current_payments";i:1;s:26:"ms_membership_max_payments";s:0:"";s:24:"ms_membership_start_date";a:3:{s:4:"year";s:4:"2014";s:5:"month";s:1:"2";s:3:"day";s:2:"13";}s:27:"ms_membership_should_expire";b:0;s:24:"ms_membership_expiration";a:3:{s:4:"year";s:4:"2014";s:5:"month";s:1:"2";s:3:"day";s:2:"13";}s:20:"ms_membership_status";i:3;s:7:"contact";i:1;}
I keep getting this error:
Warning: Invalid argument supplied for foreach()
This is my code thus far:
$fixed = preg_replace_callback(
'/s:([0-9]+):\"(.*?)\";/',
function ($matches) { return "s:".strlen($matches[2]).':"'.$matches[2].'";'; },
$data
);
$original_array = unserialize($fixed);
foreach ($original_array as $key => $value) {
echo $value['profile_membership_type'];
};
check with if condition before iteration
if(is_array($original_array) && !empty($original_array)){
foreach ($original_array as $key => $value) {
echo $value['profile_membership_type'];
}
}
Just cast to an array.
foreach ( (array) $original_array as $key => $value) {
echo $value['profile_membership_type'];
}
You can easily check to see if the variable you're iterating through is an array;
if(isset($original_array) && is_array($original_array)) {
foreach ( $original_array as $key => $value) {
echo $value['profile_membership_type'];
}
}
Edited to include a check to ensure the variable exists.
You have a php serialized string.
I presume the leading f in your question is a typo, as the rest is a valid serialized array:
$array = unserialize('a:12:{s:23:"profile_membership_type";s:4:"Full";s:21:"ms_membership_add_new";s:0:"";s:18:"ms_membership_mpid";s:0:"";s:25:"ms_membership_amount_paid";s:0:"";s:32:"ms_membership_transaction_number";s:0:"";s:30:"ms_membership_current_payments";i:1;s:26:"ms_membership_max_payments";s:0:"";s:24:"ms_membership_start_date";a:3:{s:4:"year";s:4:"2014";s:5:"month";s:1:"2";s:3:"day";s:2:"13";}s:27:"ms_membership_should_expire";b:0;s:24:"ms_membership_expiration";a:3:{s:4:"year";s:4:"2014";s:5:"month";s:1:"2";s:3:"day";s:2:"13";}s:20:"ms_membership_status";i:3;s:7:"contact";i:1;}');
var_dump($array);
/*
array (size=12)
'profile_membership_type' => string 'Full' (length=4)
'ms_membership_add_new' => string '' (length=0)
'ms_membership_mpid' => string '' (length=0)
'ms_membership_amount_paid' => string '' (length=0)
'ms_membership_transaction_number' => string '' (length=0)
'ms_membership_current_payments' => int 1
'ms_membership_max_payments' => string '' (length=0)
'ms_membership_start_date' =>
array (size=3)
'year' => string '2014' (length=4)
'month' => string '2' (length=1)
'day' => string '13' (length=2)
'ms_membership_should_expire' => boolean false
'ms_membership_expiration' =>
array (size=3)
'year' => string '2014' (length=4)
'month' => string '2' (length=1)
'day' => string '13' (length=2)
'ms_membership_status' => int 3
'contact' => int 1
*/
Note that there is only a single profile_membership_type element, so there is no need to loop:
echo $array['profile_membership_type']; // Full
I want the array to merge into a key value pair. look at the example below
Here is my code and array $aExtraFilter
array (size=4)
0 =>
array (size=2)
'key' => string 'CookTech' (length=8)
'value' => string 'Broil' (length=5)
1 =>
array (size=2)
'key' => string 'CookTech' (length=8)
'value' => string 'Pan Fry' (length=7)
2 =>
array (size=2)
'key' => string 'CookSkills' (length=10)
'value' => string 'Intro' (length=5)
3 =>
array (size=2)
'key' => string 'CookSkills' (length=10)
'value' => string 'Knife Skills' (length=12)
Here is my code:
$aExtraFilter2 = [];
$extrafilterkey = '';
$extrafiltervalue = [];
foreach ($aExtraFilter as $key => $value) {
$extrafilterkey = $value['key'];
$aExtraFilter2[$extrafilterkey] = [];
array_push($extrafiltervalue, $value['value']);
$aExtraFilter2[$extrafilterkey] = implode(',', $extrafiltervalue);
}
var_dump($aExtraFilter2);
the output is :
array (size=2)
'CookTech' => string 'Broil,Pan Fry' (length=13)
'CookSkills' => string 'Broil,Pan Fry,Intro,Knife Skills' (length=32)
I want it to look like this:
array (size=2)
'CookTech' => string 'Broil,Pan Fry' (length=13)
'CookSkills' => string 'Intro,Knife Skills' (length=32)
I think I'm almost there but I guess I need some help.
This line does nothing because it is superseded just a bit later as the same variable is being set:
$aExtraFilter2[$extrafilterkey] = [];
This line appends to the array regardless of what you have as $value['key'], which is why you get all keys lumped together in the output:
array_push($extrafiltervalue, $value['value']);
This will produce a desired output:
// fill array of arrays
$aExtraFilter2 = [];
foreach ($aExtraFilter as $key => $value) {
if (!array_key_exists($value['key'], $aExtraFilter2)) $aExtraFilter2[$value['key']] = [];
$aExtraFilter2[$value['key']][] = $value['value'];
}
// convert to string (if needed at all, depends on what you're doing later)
foreach ($aExtraFilter2 as $key => $set) {
$aExtraFilter2[$key] = join(',', $set);
}
The typical way to code this is by creating a temporary structure, based on the key and comprising an array with the values:
$tmp = [];
foreach ($aExtraFilter as $pair) {
$tmp[$pair['key']][] = $pair['value'];
}
The structure would look like this afterwards:
[
'CookTech' => ['Broil', 'Pan Fry'],
'CookSkills' => ['Intro', 'Knife Skills'],
]
Then, you map that array against the representation you want to have:
$aExtraFilter2 = array_map(function($values) {
return join(',', $values);
}, $tmp);
See also: array_map()
How can I check if the values are unique in an array based on the key value? Below is the out put of the array. I want to remove duplicate values based on the "id" key. If you check below, the 2nd & 3rd array are same except for the "role" value. Because of this, array_unique is not working on this array.
array
0 =>
array
'id' => string '1521422' (length=7)
'name' => string 'David Alvarado' (length=14)
'role' => string 'associate producer ' (length=20)
1 =>
array
'id' => string '0098210' (length=7)
'name' => string 'Cristian Bostanescu' (length=19)
'role' => string 'line producer: Romania (as Cristi Bostanescu)' (length=46)
2 =>
array
'id' => string '1266015' (length=7)
'name' => string 'Bruno Hoefler' (length=13)
'role' => string 'co-producer ' (length=13)
3 =>
array
'id' => string '1266015' (length=7)
'name' => string 'Bruno Hoefler' (length=13)
'role' => string 'executive producer ' (length=20)
4 =>
array
'id' => string '1672379' (length=7)
'name' => string 'Alwyn Kushner' (length=13)
'role' => string 'associate producer ' (length=20)
Try this one:
<?php
$array = array(
array('id' => 1, 'text' => 'a'),
array('id' => 2, 'text' => 'b'),
array('id' => 1, 'text' => 'c'),
array('id' => 3, 'text' => 'd')
);
$array = array_filter($array, function ($item) {
static $found = array();
if (isset($found[$item['id']])) return false;
$found[$item['id']] = true;
return true;
});
var_dump($array);
This works as of PHP 5.3 (because of the closure and static statement).
cf. http://php.net/manual/en/function.array-filter.php for more information. I tested the statement within loops, it works there as well.
Basically you want to implement a variation of array_unique that does what you want:
function array_unique_multi($arr,$key='id') {
// $arr is the array to work on
// $key is the key to make unique by
$ret = Array();
foreach($arr as $v) {
if( !isset($ret[$v[$key]])) $ret[$v[$key]] = $k;
}
return array_values($ret);
}
You can use this code:
// assuming $arr is your original array
$narr = array();
foreach($arr as $key => $value) {
//$narr[json_encode($value)] = $key;
if (!array_key_exists($value["id"], $narr))
$narr[$value["id"]] = $key;
}
$narr = array_flip($narr);
foreach($arr as $key => $value) {
if (!array_key_exists($key, $narr))
unset($arr[$key]);
}
print_r($arr); // will have no duplicates