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

后端 未结 5 1970
甜味超标
甜味超标 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条回答
  •  猫巷女王i
    2021-01-30 10:24

    For a fast and open solution (without doubling array using array_keys and similar):

    /**
     * Array map alternative to work with values and keys of single array.
     *
     * Callable receives $value and $index of $sourceArray as arguments
     * If keys are not preserved via $preserveKeys - $keyCallback can be used to determinate key
     *
     * @param array $sourceArray
     * @param callable|null $valueCallback
     * @param callable|null $keyCallback
     * @param bool $preserveKeys
     * @return array
     */
    function array_map_indexed(
        array $sourceArray,
        ?callable $valueCallback = null,
        ?callable $keyCallback = null,
        bool $preserveKeys = true
    ): array {
        $newArray = [];
    
        foreach ($sourceArray as $key => $value) {
            if ($preserveKeys) {
                $newArray[$keyCallback ? $keyCallback($value, $key) : $key] = $valueCallback
                    ? $valueCallback($value, $key)
                    : $value;
            } else {
                $newArray[] = $valueCallback
                    ? $valueCallback($value, $key)
                    : $value;
            }
        }
    
        return $newArray;
    }
    

    Usage examples:

    $result = array_map_indexed(
        [
            'a' => 'aValue',
            'b' => 'bValue',
        ],
        function($value, $index) {
            return [$value, $index];
        },
    );
    //Array ( [a] => Array ( [0] => aValue [1] => a ) [b] => Array ( [0] => bValue [1] => b ) )
    
    $result = array_map_indexed(
        [
            'a' => 'aValue',
            'b' => 'bValue',
        ],
        function($value, $index) {
            return $index.$value;
        },
        null,
        false
    );
    //Array ( [0] => aaValue [1] => bbValue )
    
    $result = array_map_indexed(
        [
            'a' => 'aValue',
            'b' => 'bValue',
        ],
        null,
        function($value, $index) {
            return $value === 'aValue' ? 'specificKey' : $index;
        },
    );
    //Array ( [specificKey] => aValue [b] => bValue )
    

提交回复
热议问题