In PHP, how do you change the key of an array element?

后端 未结 23 2375
逝去的感伤
逝去的感伤 2020-11-22 03:45

I have an associative array in the form key => value where key is a numerical value, however it is not a sequential numerical value. The key is actually an I

23条回答
  •  梦毁少年i
    2020-11-22 04:22

    You can use this function based on array_walk:

    function mapToIDs($array, $id_field_name = 'id')
    {
        $result = [];
        array_walk($array, 
            function(&$value, $key) use (&$result, $id_field_name)
            {
                $result[$value[$id_field_name]] = $value;
            }
        );
        return $result;
    }
    
    $arr = [0 => ['id' => 'one', 'fruit' => 'apple'], 1 => ['id' => 'two', 'fruit' => 'banana']];
    print_r($arr);
    print_r(mapToIDs($arr));
    

    It gives:

    Array(
        [0] => Array(
            [id] => one
            [fruit] => apple
        )
        [1] => Array(
            [id] => two
            [fruit] => banana
        )
    )
    
    Array(
        [one] => Array(
            [id] => one
            [fruit] => apple
        )
        [two] => Array(
            [id] => two
            [fruit] => banana
        )
    )
    

提交回复
热议问题