23

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

3 Answers 3

39
$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);
Sign up to request clarification or add additional context in comments.

1 Comment

unfortunately won't work if you're trying to modify the keys
1

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);

Comments

0
function realEscape($data){
    global $connection;
        $array=[];
  do{

    if(is_string($data)){
        $array= mysqli_real_escape_string($connection,$data);
       break; 
    }


foreach($data as $key =>$value){
      $array[$key]=is_array($value)?realEscape($value):mysqli_real_escape_string($connection,$value);  
}


}while(0);
return $array;}

A simple solution fit anywhere. Cheers !

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.