Using mysql_real_escape_string in a multidimensional array in php - php

I am working on a big script which will generate some string or array or multidimensional array i want use mysql_real_escape_string for all array / string
for that this i tried the below code
function check($data) {
if(!is_array($data)) {
return mysql_real_escape_string($data);
} else if (is_array($data)) {
$newData = array();
foreach($data as $dataKey => $dataValue){
if(!is_array($dataValue)){
$key = mysql_real_escape_string($dataKey);
$value = mysql_real_escape_string($dataValue);
$newData[$key] = $value;
}
}
return $newData;
}
}
if i use like this check('saveme'); this returns value
if i pass a array it returns corrent value [ check(array('a','b','c',1,2,3)) ]
if i pass multidimensional array i get [check(array(array('a',array('a','b','c',1,2,3),'c',1,2,3),'b',array('a','b','c',1,2,3),1,2,3))]
A kind note i want to use mysql_real_escape_string for array key too.

You can use array_walk_recursive function, to go throw all leaves of the array, and escape values:
array_walk_recursive($array, function(&$leaf) {
if (is_string($leaf))
$leaf = mysql_real_escape_string($leaf);
});
Also, it is good to follow data consistency rules, and do not use !is_array(), but is_string(), because mysql_real_escape_string takes string params, not !string.
Unfortunately, array_walk_recursive is designed so, that it can't edit keys. If you need edit keys, you may want to write your own recursive function. I don't want to copy answer, you can find it here

You can use this function :
(MyStringEscapeFunc() is your custom escape function)
function escape_recursive($arr){
if(is_array($arr)){
$temp_arr = array();
foreach ($arr as $key=>$value){
$temp_arr[MyStringEscapeFunc($key)] = escape_recursive($value);
}
return $temp_arr;
}else{
return MyStringEscapeFunc($arr);
}
}
Example Result :
//Before :
Array (
[0] => Array (
[0] => foo'bar
[1] => bar'baz
)
[1] => foob'ar
[2] => Array ( [foo'baz] => baz'foo )
)
//After :
Array (
[0] => Array (
[0] => foo\'bar
[1] => bar\'baz
)
[1] => foob\'ar
[2] => Array ( [foo\'baz] => baz\'foo )
)

Related

Build dynamic associative array from simple array in php

I have an array as given below
$arr = ['Product', 'Category', 'Rule'];
This can be a dynamic array meaning it can sometimes have between 1-5 elements inside it and its value can change.
How can we create an array as given below from the above one in a dynamic manner.
$json['Product']['Category']['Rule'] = 'fixed';
Simply put am just trying to make a multidimensional array from the values I get from the $arr.
This function should do it.
function nestArray($arr, $value) {
if (!count($arr)) {
return $value;
}
foreach (array_reverse($arr) as $key) {
$new = [$key => $value];
$value = $new;
}
return $new;
}
Example
$arr = ['Product', 'Category', 'Rule'];
$nested = nestArray($arr, 'fixed');
print_r($nested);
Output
Array
(
[Product] => Array
(
[Category] => Array
(
[Rule] => fixed
)
)
)

PHP foreach assigning of array

I'm trying to read recursively into an array until I'm getting a string. Then I try to explode it and return the newly created array. However, for some reason it does not assign the array:
function go_in($arr) { // $arr is a multi-dimensional array
if (is_array($arr))
foreach($arr as & $a)
$a = go_in($a);
else
return explode("\n", $arr);
}
EDIT:
Here's the array definition as printed by print_r:
Array
(
[products] => Array
(
[name] => Arduino Nano Version 3.0 mit ATMEGA328P
[id] => 10005
)
[listings] => Array
(
[category] =>
[title] => This is the first line
This is the second line
[subtitle] => This is the first subtitle
This is the second subtitle
[price] => 24.95
[quantity] =>
[stock] =>
[shipping_method] => Slow and cheap
[condition] => New
[defects] =>
)
[table_count] => 2
[tables] => Array
(
[0] => products
[1] => listings
)
)
I'd use this:
array_walk_recursive($array,function(&$value,$key){
$value = explode("\n",$value);
});
However, this fixes your function:
function &go_in(&$arr) { // $arr is a multi-dimensional array
if (is_array($arr)){
foreach($arr as & $a) $a = go_in($a);
} else {
$arr = explode("\n", $arr);
}
return $arr;
}
When writing nested conditions/loops - always add braces for better readability and to prevent bugs.. Also you should return the go_in function, because it is recursive, it needs to be passed to the calling function instance.
function go_in($arr) { // $arr is a multi-dimensional array
if (is_array($arr))
{
foreach($arr as &$a)
{
return go_in($a);
}
}
else
{
return ($arr);
}
}
The original array was not returned in the function:
function go_in($arr) {
if (is_array($arr))
foreach($arr as &$a)
$a = go_in($a);
else
if (strpos($arr, "\n") !== false)
return explode("\n", $arr);
return $arr;
}
EDIT:
Now, it only really edits the strings that contain a linebreak. Before it would edit every string which meant that every string was returned as an array.

search associative array by value

I'm fetching some JSON from flickrs API. My problem is that the exif data is in different order depending on the camera. So I can't hard-code an array number to get, for instance, the camera model below. Does PHP have any built in methods to search through associative array values and return the matching arrays? In my example below I would like to search for the [label] => Model and get [_content] => NIKON D5100.
Please let me know if you want me to elaborate.
print_r($exif['photo']['exif']);
Result:
Array
(
[0] => Array
(
[tagspace] => IFD0
[tagspaceid] => 0
[tag] => Make
[label] => Make
[raw] => Array
(
[_content] => NIKON CORPORATION
)
)
[1] => Array
(
[tagspace] => IFD0
[tagspaceid] => 0
[tag] => Model
[label] => Model
[raw] => Array
(
[_content] => NIKON D5100
)
)
[2] => Array
(
[tagspace] => IFD0
[tagspaceid] => 0
[tag] => XResolution
[label] => X-Resolution
[raw] => Array
(
[_content] => 240
)
[clean] => Array
(
[_content] => 240 dpi
)
)
$key = array_search('model', array_column($data, 'label'));
In more recent versions of PHP, specifically PHP 5 >= 5.5.0, the function above will work.
To my knowledge there is no such function. There is array_search, but it doesn't quite do what you want.
I think the easiest way would be to write a loop yourself.
function search_exif($exif, $field)
{
foreach ($exif as $data)
{
if ($data['label'] == $field)
return $data['raw']['_content'];
}
}
$camera = search_exif($exif['photo']['exif'], 'model');
$key = array_search('Model', array_map(function($data) {return $data['label'];}, $exif))
The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function. In this case we are returning the label.
The array_search() function search an array for a value and returns the key. (in this case we are searching the returned array from array_map for the label value 'Model')
This would be fairly trivial to implement:
$model = '';
foreach ($exif['photo']['exif'] as $data) {
if ($data['label'] == 'Model') {
$model = $data['raw']['_content'];
break;
}
}
foreach($exif['photo']['exif'] as $row) {
foreach ($row as $k => $v) {
if ($k == "label" AND $v == "Model")
$needle[] = $row["raw"];
}
}
print_r($needle);
The following function, searches in an associative array both for string values and values inside other arrays. For example , given the following array
$array= [ "one" => ["a","b"],
"two" => "c" ];
the following function can find both a,b and c as well
function search_assoc($value, $array){
$result = false;
foreach ( $array as $el){
if (!is_array($el)){
$result = $result||($el==$value);
}
else if (in_array($value,$el))
$result= $result||true;
else $result= $result||false;
}
return $result;
}
$data = [
["name"=>"mostafa","email"=>"mostafa#gmail.com"],
["name"=>"ali","email"=>"ali#gmail.com"],
["name"=>"nader","email"=>"nader#gmail.com"]];
chekFromItem($data,"ali");
function chekFromItem($items,$keyToSearch)
{
$check = false;
foreach($items as $item)
{
foreach($item as $key)
{
if($key == $keyToSearch)
{
$check = true;
}
}
if($check == true)
{break;}
}
return $check;}
As far as I know , PHP does not have in built-in search function for multidimensional array. It has only for indexed and associative array. Therefore you have to write your own search function!!

PHP multidimensional array to simple array

Which method is best practice to turn a multidimensional array
Array ( [0] => Array ( [id] => 11 ) [1] => Array ( [id] => 14 ) )
into a simple array? edit: "flattened" array (thanks arxanas for the right word)
Array ( [0] => 11 [1] => 14 )
I saw some examples but is there an easier way besides foreach loops, implode, or big functions? Surely there must a php function that handles this. Or not..?
$array = array();
$newArray = array();
foreach ( $array as $key => $val )
{
$temp = array_values($val);
$newArray[] = $temp[0];
}
See it here in action: http://viper-7.com/sWfSbD
Here you have it in function form:
function array_flatten ( $array )
{
$out = array();
foreach ( $array as $key => $val )
{
$temp = array_values($val);
$out[] = $temp[0];
}
return $out;
}
See it here in action: http://viper-7.com/psvYNO
You could use array_walk_recursive to flatten an array.
$ret = array();
array_walk_recursive($arr, function($var) use (&$ret) {
$ret[] = $var;
});
var_dump($ret);
If you have a multidimensional array that shouldn't be a multidimensional array (has the same keys and values) and it has multiple depths of dimension, you can just use recursion to loop through it and append each item to a new array. Just be sure not to get a headache with it :)
Here's an example. (It's probably not as "elegant" as xdazz", but it's an alternate without using "use" closure.) This is how the array might start out like:
Start
array (size=2)
0 =>
array (size=1)
'woeid' => string '56413072' (length=8)
1 =>
array (size=1)
'woeid' => string '56412936' (length=8)
Then you might want to have something like this:
Target
array (size=2)
0 => string '56413072' (length=8)
1 => string '56412936' (length=8)
You can use array_walk_recursive
Code
$woeid = array();
array_walk_recursive($result['results']['Result'], function ($item, $key, $woeid) {
if ($key == 'woeid') {
$woeid[] = $item;
}
}, &$woeid);

How to urlencode a multidimensional array?

I have searched hi and low for a solution. I have a dynamic multidimensional array I need to break up and urlencode. The number of items will change but they will always have the same keys.
$formFields = Array (
[0] => Array ( [form_name] => productID [form_value] => 13 )
[1] => Array ( [form_name] => campaign [form_value] => email#gmail.com )
[2] => Array ( [form_name] => redirect [form_value] => http://example.com ) )
Each array has a Form Name and a Form Value.
This is what I'm trying to get to:
$desired_results =
productID => 13
campaign => email#gmail.com
redirect => http://example.com
Every time I try and split them up I end up with: form_name => productID or something like that.
I'm trying to take the results and then urlencode them:
productID=13&campaign=email&gmail.com&redirect=http://example.com&
you can use serialize and the unserialize:
$str = urlencode(serialize($formFields));
and then to decode it:
$formFields = unserialize(urldecode($str));
This will return the values regardless of the names of the keys.
$result = array();
foreach ($formFields as $key => $value)
{
$tmp = array_values($value);
$result[$tmp[0]] = $tmp[1];
}
print(http_build_query($result));
The foreach loops through the main array, storing the subarrrays in the variable $value. The function array_values return all the values from each array as a new numeric array. The value of [form_name] will be stored in the first index, [form_value] in the second.
The built in http_build_query function will return a urlencoded string.
Here's my straightforward function for doing such a thing:
function array_urlencode($data) {
if (is_array($data)) {
foreach($data as $k => $v) $data_temp[urlencode($k)]=array_urlencode($v);
return $data_temp;
} else {
return urlencode($data);
}
}
<!-- Encode entire array here -->
function encode(&$item, $key) {
$item = rawurlencode($item);
}
array_walk_recursive($input_array, 'encode');

Categories