魏长东

weichangdong

php的array_map函数高级应用

想实现给 一个二维数组中每个数组,都添加一个数据。

class wcd{
    public static $qq = array(
        array(
        'fromKKuid' =>1,
        'toKKuid' => 3,
        ),
        array(
        'fromKKuid' => 33,
        'toKKuid' => 44,
        ),
    );
//想实现成这样的:给每个数组加一个type数值
public $wcd2 = array(
    array(
    'fromKKuid' =>1,
    'toKKuid' => 3,
    'type' => 3,
    ),
    array(
    'fromKKuid' => 33,
    'toKKuid' => 44,
    'type' => 3,
    ),
);

public static function test(){
    $data = array_map(array(__CLASS__, 'myMerge'), static::$qq);
    //用self也可以
    $data = array_map(array('self', 'myMerge'), static::$qq);
    //用static也可以
    $data = array_map(array('static', 'myMerge'), static::$qq);
    return $data;
}

public function myMerge($data)
{
    return array_merge($data, array('type' => 3));
}

}
$wcd =new wcd();
$re = wcd::test();
print_r($re);

 

运行结果:

Array ( [0] => Array ( [fromKKuid] => 1 [toKKuid] => 3 [type] => 3 ) [1] => Array ( [fromKKuid] => 33 [toKKuid] => 44 [type] => 3 ) )