Using the Array_map Function

Asked

Viewed 46 times

1

I’m trying to use the function array_map to apply a function to all indices of a array after executing the code it brings this array

array (size=13)
  0 => 
    array (size=1)
      'name' => string 'a' (length=20)
  1 => 
    array (size=1)
      'name' => string 'b' (length=25)
  2 => 
    array (size=1)
      'name' => string 'c' (length=20)
  3 => 
    array (size=1)
      'name' => string 'd' (length=19)

what I want and that all the values of each index be uppercase used so

array_map('strtoupper', $Results);

after executing it from the error as precise informs the index this way

array_map('strtoupper', $Results[0]);

ai it works more apply the function only at index 0 getting like this

array (size=13)
      0 => 
        array (size=1)
          'name' => string 'A' (length=20)
      1 => 
        array (size=1)
          'name' => string 'b' (length=25)
      2 => 
        array (size=1)
          'name' => string 'c' (length=20)
      3 => 
        array (size=1)
          'name' => string 'd' (length=19)

more I want to apply in all indexes.

1 answer

1


You need to call twice array_map, one that will iterate on the arrays and the other who will call the function to strtoupper, example:

<?php

$array = array (
        array('name' => 'a'),
        array('name' => 'b'),
        array('name' => 'c'),
        array('name' => 'd'),
    );

$result = array_map(function($a){ return array_map('strtoupper', $a); }, $array);

print_r($result);

Exit:

Array
(
    [0] => Array
        (
            [name] => A
        )    
    [1] => Array
        (
            [name] => B
        )    
    [2] => Array
        (
            [name] => C
        )    
    [3] => Array
        (
            [name] => D
        )    
)

Online Example

  • Or https://ideone.com/L0EyuV

  • also @bfavaretto

Browser other questions tagged

You are not signed in. Login or sign up in order to post.