Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_map for multidimensional arrays

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

like image 261
kalpaitch Avatar asked Nov 03 '10 09:11

kalpaitch


People also ask

What is the syntax for multidimensional array?

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.

What is the use of array_map in PHP?

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.

Can C language handle multidimensional arrays?

In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, float x[3][4];

Which library can be used to support multidimensional array?

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.


2 Answers

$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);
like image 140
Mark Baker Avatar answered Oct 17 '22 12:10

Mark Baker


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);
like image 24
Minwork Avatar answered Oct 17 '22 12:10

Minwork