开发者

array_map for multidimensional arrays

开发者 https://www.devze.com 2023-01-23 01:28 出处:网络
I am trying to find a soluti开发者_JS百科on to using array_map(\'mysql_real_escape_string\', $data); on multidimensional arrays, If $data is multidimensional, php returns an error. cheers$array = arra

I am trying to find a soluti开发者_JS百科on to using array_map('mysql_real_escape_string', $data); on multidimensional arrays, If $data is multidimensional, php returns an error. cheers


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


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 !

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号