PHP: Can I get the index in an array_map function?

后端 未结 5 1968
甜味超标
甜味超标 2021-01-30 09:57

I\'m using a map in php like so:

function func($v) {
    return $v * 2;
}

$values = array(4, 6, 3);
$mapped = array_map(func, $values);
var_dump($mapped);
         


        
5条回答
  •  爱一瞬间的悲伤
    2021-01-30 10:43

    Very simple:

    Only array_map fuction: does not have index key!

     $params = [4,6,2,11,20];
    
     $data = array_map(function($v) { return ":id{$v}";}, $params);
    
     array (size=5)
      0 => string ':id4' (length=4)
      1 => string ':id6' (length=4)
      2 => string ':id2' (length=4)
      3 => string ':id11' (length=5)
      4 => string ':id20' (length=5)
    

    Now, combine with array_keys:

    $data = array_map(
        function($k) use ($params) { return ":id{$k}_${params[$k]}"; },
        array_keys($params)
     );
    
    array (size=5)
      0 => string ':id0_4' (length=6)
      1 => string ':id1_6' (length=6)
      2 => string ':id2_2' (length=6)
      3 => string ':id3_11' (length=7)
      4 => string ':id4_20' (length=7)
    

提交回复
热议问题