我有这些对象数组,
array (
[0] => DataCON Object (
[id] => 2
[first_name] => Urek
[last_name] => Mazino
[email] => hello@world.com
[phone] => 000-444-5555
[date] => 2016-02-11 14:46:38
.
.
.
.
)
[1] => DataCON Object (
[ID] => 3
.
.
.
.
)
)
我创建了一个函数,该函数循环遍历每个对象并根据另一个函数提供的模板返回值,但问题是当我有超过 1 个对象结果时,它只会杀死服务器,我的目标是让<span class="{fname}">{ID} - {email}</span>
返回<span class="Urek">2 - hello@world.com</span>
这是我的代码,
class Kill_Bill {
.
.
.
public function _get_data( $template ) {
$object = $this->the_data_object();
if ( !$object ) return ' to me';
$to_her = '';
foreach ( $object as $obj ) {
$tags = array(
'{id}' => $obj->id,
'{fname}' => $obj->first_name,
'{lname}' => $obj->last_name,
'{email}' => $obj->email,
.
. // This whole thing is killing my server with bytes exhuasted,
. // it only works fine if there's a single object in an array,
);
$to_her .= strtr( $template, $tags );
#$to_her .= str_replace('{id}', $obj->id, $template ) // This works fine.
}
return $to_her;
}
.
.
.
}
是否有更好、更快的方法代替str_replace,我可以用来用对象值替换模板值?
好吧,
您可以在同一个 str_replace()
语句中替换所有 3 个(如果需要,或更多)占位符。search
和 replace
参数可以是要查找的事物和要替换它们的事物的数组。
$to_her .= str_replace( array('{id}', '{fname}', '{email}'),
array($obj->id, $obj->first_name, $obj->email),
$template );