문제

PHP 와 같은 기능'array_map'을 콜백이 될 수 있습니다 간단한 함수하거나 클래스 또는 개체방법:

$array2 = array_map('myFunc', $array);  

$array2 = array_map(array($object, 'myMethod'), $array);

하지만 구문을 통과하는 방법밖에 반복하여 현재 개체(다음과 같'호출'in Prototype.js)?도록 다음 사용될 수 있:

$array2 = array_map('myMethod', $array);

의 효과

foreach($array as $obj) $array2[] = $obj->myMethod();

분명히 나는 이 양식을 사용하거나,내가 쓸 수 있는 래퍼 함수 호출,심지어는 인라인 요소입니다.하지만 이후'myMethod'은 이미 방법이 될 것으로 보인 가운 주택하고 다음 중 하나를 수행합니다.

도움이 되었습니까?

해결책

function obj_array_map($method, $arr_of_objects) {
    $out = array();
    $args = array_slice(func_get_args(), 2);
    foreach ($arr_of_objects as $key => $obj) {
        $out[$key] = call_user_func_array(Array($obj, $method), $args);
    }
    return $out;
}

// this code
$a = Array($obj1, $obj2);
obj_array_map('method', $a, 1, 2, 3);

// results in the calls:
$obj1->method(1, 2, 3);
$obj2->method(1, 2, 3);

다른 팁

현재는 아닙니다.때 php5.3 온를 사용할 수 있는 구문은 다음과 같습니다.

$array2 = array_map(function($obj) { return $obj->myMethod(); }, $array);

기본적으로,아닙니다.이 없는 특별한 구문을 확인이 가능합니다.

나는 생각할 수 있습의 애호가의 방법에 이렇게 PHP5.3 으로 보고,거의 항상 하나 이상의 방법으로 일을 하는 것이 PHP 지만,나는 그것을 말하지 않을 것 foreach 예제:

$x = array_reduce(
    $array_of_objects, 
    function($val, $obj) { $val = array_merge($val, $obj->myMethod()); return $val; },
    array() 
);

그냥 귀하의 foreach:)

<?php

// $obj->$method(); works, where $method is a string containing the name of the
// real method
function array_map_obj($method, $array) {
    $out = array();

    foreach ($array as $key => $obj)
        $out[$key] = $obj->$method();

    return $out;    
}

// seems to work ...

class Foo {
    private $y = 0;
    public function __construct($x) {
        $this->y = $x;
    }
    public function bar() {
        return $this->y*2;
    }
}

$objs = array();
for ($i=0; $i<20; $i++)
    $objs[] = new Foo($i);

$res = array_map_obj('bar', $objs);

var_dump($res);

?>

voila!

이것은 비트의 바보 같은 대답은,하지만 당신은 서브 클래스 ArrayObject 고 사용하는 대신 정상적인 배열:

<?php

class ArrayTest extends ArrayObject {
    public function invokeMethod() {
        $result = array();
        $args = func_get_args();
        $method = array_shift($args);
        foreach ($this as $obj) {
            $result[] = call_user_func_array(array($obj, $method), $args);
        }
        return $result;
    }
}

//example class to use
class a { 
    private $a;
    public function __construct($a) { 
        $this->a = $a; 
    }

    public function multiply($n) {
        return $this->a * $n;
    }
 }

//use ArrayTest instance instead of array
$array = new ArrayTest();
$array[] = new a(1);
$array[] = new a(2);
$array[] = new a(3);

print_r($array->invokeMethod('multiply', 2));

출력한다:

Array
(
    [0] => 2
    [1] => 4
    [2] => 6
)

내가 사용하는 것 create_function() 다.음...작성 일시적 기능에 대한 array_map 를 기다리는 동안 PHP5.3

$func = create_function('$o', '$o->myMethod();');
array_map($func, $objects);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top