我在开发时经常遇到的一种模式是尝试从一组对象中收集一个列/属性值到一个数组中.例如:
$ids = array();
foreach ($documents as $document) {
$ids[] = $document->name;
}
Run Code Online (Sandbox Code Playgroud)
我是唯一一个碰到这个的人吗?PHP有没有办法用更少的行来解决这个问题?我看了,却一无所获.
由于我使用MVC框架,因此我可以访问BaseUtil类,该类包含不适合任何特定类的常用函数.同事提出的一个解决方案是:
class BaseUtil
{
public static function collect($collection, $property) {
$values = array();
foreach ($collection as $item) {
$values[] = $item->{$property};
}
return $values;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我可以这样做:
$ids = BaseUtil::collect($documents, 'name');
Run Code Online (Sandbox Code Playgroud)
不是太寒酸.其他人还有其他想法吗?我是疯了还是这看起来像PHP应该在很久以前解决的问题?
我正在尝试构建一个函数,我可以将其用作我正在映射的RxPy流的处理程序.我所需要的函数需要访问定义该变量的范围之外的变量,对我而言,这意味着我需要使用某种闭包.所以我到达functools.partial来关闭一个变量并返回一个部分函数,我可以作为观察者传递给我的流.
但是,这样做会导致以下结果:
Traceback (most recent call last):
File "retry/example.py", line 46, in <module>
response_stream = message_stream.flat_map(functools.partial(message_handler, context=context))
File "/home/justin/virtualenv/retry/local/lib/python2.7/site-packages/rx/linq/observable/selectmany.py", line 67, in select_many
selector = adapt_call(selector)
File "/home/justin/virtualenv/retry/local/lib/python2.7/site-packages/rx/internal/utils.py", line 37, in adapt_call_1
argnames, varargs, kwargs = getargspec(func)[:3]
File "/usr/lib/python2.7/inspect.py", line 816, in getargspec
raise TypeError('{!r} is not a Python function'.format(func))
TypeError: <method-wrapper '__call__' of functools.partial object at 0x2ce6cb0> is not a Python function
Run Code Online (Sandbox Code Playgroud)
以下是一些重现问题的示例代码:
from __future__ import absolute_import
from rx import Observable, Observer
from pykafka import KafkaClient
from pykafka.common import …Run Code Online (Sandbox Code Playgroud)