Home >Backend Development >PHP Tutorial >Examples of how to use array_map() and other functions in the php framework

Examples of how to use array_map() and other functions in the php framework

黄舟
黄舟Original
2017-09-06 09:40:001318browse
  • There are always some special needs, so I found this function.

  • The following is excerpted from the official manual array_map()

    • callback -- callback function, applied to each each element in the array.

    • array1 -- Array, traverse and run the callback function.

    • Array list, each traverses and runs the callback function.

    • array_map -- Apply a callback function to each element of the array

    • array array_map ( callable $callback , array $array1 [, array $ ... ] )

    • array_map(): Returns an array, which is the array after applying the callback function to each element of array1. The number of callback function parameters and the number of arrays passed to array_map() must be the same.

    • Parameters

    • Return value -- Returns an array containing all elements of array1 after callback function processing.

    • Example


##

<?php
    $arr = [
        [&#39;a&#39; => &#39;aa&#39;,&#39;b&#39; => &#39;bb&#39;,],
        [&#39;c&#39; => &#39;cc&#39;,&#39;d&#39; => &#39;dd&#39;,],
        [&#39;e&#39; => &#39;ee&#39;,&#39;f&#39; => &#39;ff&#39;,],
    ];

    function test($v){        
    $v[&#39;add&#39;] = 0;
        return $v;
    }    $arr = array_map("test",$arr);
    print_r($arr);?>

Output result


Array(
    [0] => Array
        (
            [a] => aa            
            [b] => bb            
            [add] => 0
        )

    [1] => Array
        (
            [c] => cc            
            [d] => dd            
            [add] => 0
        )

    [2] => Array
        (
            [e] => ee            
            [f] => ff            
            [add] => 0
        ))

  • Framework (ThinkPHP) example

  • <?php
    namespace User\Controller;
    
    use Common\Controller\ManagerController;
    
    class DataController extends Controller
    {
        public function get_data()
        {
            $arr = [
                // 数据填充
            ];
            
            $arr = array_map([$this,&#39;_add_param&#39;],$arr);
            dump($arr);
        } 
    
        private function _add_param($value){
            $value[&#39;add&#39;] = &#39;xxx&#39;;
            return $value;
        }
    }

The above is the detailed content of Examples of how to use array_map() and other functions in the php framework. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn