I am trying to find a solution to using array_map('mysql_real_escape_string', $data);
on multidimensional arrays, If $data is multidimensional, php returns an error. cheers
Size of multidimensional arrays: The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int[][] x = new int[10][20] can store a total of (10*20) = 200 elements.
The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.
In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, float x[3][4];
Synopsis. The Boost Multidimensional Array Library provides a class template for multidimensional arrays, as well as semantically equivalent adaptors for arrays of contiguous data. The classes in this library implement a common interface, formalized as a generic programming concept.
$array = array( array('A' => "Hello", 'B' => "World"),
array('A' => "Goodnight", 'B' => "Vienna")
);
function myFunc(&$item, $key) {
$item = mysql_real_escape_string($item);
}
array_walk_recursive($array,'myFunc');
var_dump($array);
You can also use minwork/array to easily map any multidimensional array.
Biggest advantage of this solution over native functions is that you can map multidimensional arrays with various nesting depth also accessing their keys, for example:
$array = [
1 => [
2 => 'a',
3 => 'b',
4 => [
5 => 'c',
],
],
'test' => 'd',
];
$callback = function ($keys, $value) {
return implode('.', $keys) . " -> {$value}";
}
Arr::map($array, $callback, Arr::MAP_ARRAY_KEYS_ARRAY_VALUE) ->
[
1 => [
2 => '1.2 -> a',
3 => '1.3 -> b',
4 => [
5 => '1.4.5 -> c',
],
],
'test' => 'test -> d',
]
In your case you can simply apply mysql_real_escape_string
function (without modifying input array) to every element like this (no matter how deeply each element is nested)
$escapedData = Arr::map($data, function ($value) {
return mysql_real_escape_string($value);
}, Arr::MAP_ARRAY_VALUE_KEYS_LIST);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With