我使用的API(Oracle Service Cloud的ConnectPHP)遵循链接方法。例如:
$incident = new Incident();
$incident->CustomFields->c->make = "Same value";
$incident->StatusWithType->Status->ID = 34;
$incident->save();
如果动态生成$incident
对象的后续属性,我将如何实现相同的目标?例如:
$data = array();
$data[0]['parts'] = array('CustomFields', 'c', 'make');
$data[0]['value'] = "Some value";
$data[1]['parts'] = array('StatusWithType', 'Status', 'ID');
$data[1]['value'] = 34;
$incident = new Incident();
foreach($data as $array)
{
foreach($array['parts'] as $key)
{
// how will I generate
// (1) $incident->CustomFields->c->make = $array['value']
// (2) $incident->StatusWithType->Status->ID = $array['value']
}
}
$incident->save();
$incident = new Incident();
foreach($data as $array)
{
$parts = implode('->', $array['parts']);
$incident->{$parts} = $array['value']; // this doesn't work even though $parts is coming out with the expected pattern because I think it is converting it into a string representation
}
$incident->save();
答案 0 :(得分:1)
如果没有用户输入的风险,您可以创建所有对象键的字符串,并像这样使用eval
Comparable
OUTPUT为
compareTo()
现在您可以轻松访问$incident = new stdClass();
foreach($data as $key=>$chain){
$str = "{'".implode("'}->{'",$chain['parts'])."'}";
eval("@\$incident->$str = '$chain[value]';");
}
print_r($incident);
@kranthi在技术上是正确的(在评论中),我给出了实现。
答案 1 :(得分:0)
所以,kranthi走在了正确的轨道上。
$incident = new Incident();
foreach($data as $array)
{
$this->setDynamicFields($incident, $array['parts'], $array['value']);
}
$incident->save();
function setDynamicFields($obj, $parts, $value)
{
if(is_array($parts) && count($parts) == 3)
{
$obj->{$parts[0]}->{$parts[1]}->{$parts[2]} = ($parts[0] == 'StatusWithType' ? (int) $value: $value);
}
}
诀窍是将整个$incident
对象作为函数参数传递(我认为如果我没有错,则称为依赖注入)并使用->
作为文字而不是字符串住在变量里面。