我有以下功能可以正常工作。
function ($objects, $items = array())
{
$result = array();
foreach ($objects as $object) {
$result[$object->id] = $object->first_name . ' ' . $object->last_name;
}
return $result;
}
但是,我想传入一个数组来$items,并将其分解,这样我就不必手动指定first_name和last_name。
如果$item只是一个值(而不是数组),那么它会很简单:
$result[$object->id] = $object->$item;
但是我不知道如果$items包含多个值并且我想用空格连接它们,则如何使其工作。如下所示,但我需要将$object放在那里
$items = array('first_name', 'last_name');
$result[$object->id] = implode(' ', $items);
我想将
$item中的字符串用作$object的属性名称,我是否正确?
function ($objects, $items = array())
{
$result = array();
foreach ($objects as $object) {
$valuesToAssign = array();
foreach ($items as $property) {
$valuesToAssign[] = $object->$property;
}
$result[$object->id] = implode(' ', $valuesToAssign);
}
return $result;
}
我不知道要避免第二个foreach,但这会给你想要的结果。
不确定我是否做对了,但是这个怎么样:
function foo($objects, $items = array()) {
$result = array();
$keys = array_flip($items);
foreach ($objects as $object) {
// Cast object to array, then omit all the stuff that is not in $items
$values = array_intersect_key((array) $object, $keys);
// Glue the pieces together
$result[$object->id] = implode(' ', $values);
}
return $result;
}
演示:http://codepad.viper-7.com/l8vmGr