我是PHP的新手,在通过第三方API将一些数据提取到我的程序后,我很难动态生成对象引用。
我已撤回包含以下数据的记录集:
stdClass Object (
[adventure] => stdClass Object (
[shortname] => adventure
[name] => Adventure
[description] => Create a new column for each activity undertaken. The scouts need to complete three activities, and for each one:
Know the safety issues involved and understand the use of any equipment needed for the activity.
Show an awareness of environmental issues around the activity (such as erosion at popular climbing areas).
Know about further opportunities to take part in the chosen activities.
[picture] => graphics/badges/sc-cs-adch.png
[config] => {"sectionsneeded":"1","totalneeded":"1","sections":{"a":"3"}}
[order] => 1
[groupname] =>
[status] => 3
[userid] => 0
[table] => scouts_challenge_adventure )
[csg] => stdClass Object (
[shortname] => csg
[name] => Chief Scouts Gold
[description] =>
[picture] => graphics/badges/sc-cs-csa.png
[config] => {"sectionsneeded":"-1","totalneeded":"1","sections":{"a":"6","b":"2"}}
[order] => 0
[groupname] =>
[status] => 3
[userid] => 0
[table] => scouts_challenge_csg )
[community] => stdClass Object (
[shortname] => community
[name] => Community [description] =>
Create columns for each community project undertaken, and enter the number of hours each scout spend on them. 6 hours are required.
[picture] => graphics/badges/sc-cs-coch.png
[config] => {"sectionsneeded": -1, "totalneeded": -1, "sections": {"a":1}}
[order] => 1
[groupname] =>
[status] => 3
[userid] => 0
[table] => scouts_challenge_community )
)
我已将此数据提取到$徽章中,现在正尝试根据以下代码动态构建对此数据集的引用,以将其包含在表格中
foreach ($badges as $badge) {
$badgeShortname = $badge->shortname;
$badgeObj = '$scoutChallenge-'.'>'."$badgeShortname";
echo "<td>";
echo $badgeObj;
echo "</td>";
}
我尝试了各种方法,但我似乎无法动态地生成echo "$scoutChallenge->adventure";
的引用。此刻,我似乎唯一能让它工作的方法是使用switch语句,例如< / p>
foreach ($badges as $badge) {
$badgeShortname = $badge->shortname;
$badgeObj = '$scoutChallenge-'.'>'."$badgeShortname";
echo "<td>";
switch ($badgeShortname )
{
case 'csg':
echo "$scoutChallenge->csg";
break;
case 'adventure':
echo "$scoutChallenge->adventure";
break;
case 'community':
echo "$scoutChallenge->community";
break;
case 'creative':
echo "$scoutChallenge->creative";
break;
case 'expedition':
echo "$scoutChallenge->expedition";
break;
case 'fitness':
echo "$scoutChallenge->fitness";
break;
case 'outdoor':
echo "$scoutChallenge->outdoor";
break;
case 'outdoorplus':
echo "$scoutChallenge->outdoorplus";
break;
case 'promise':
echo "$scoutChallenge->promise";
break;
case 'global':
echo "$scoutChallenge->global";
break;
default:
echo "Not Found";
break;
}
echo "</td>";
}
}
显然不是特别可扩展。
$ scoutChallenge是我通过API引入的另一个数据集,以及与$ badges数据集共享引用的数据集。
是否有动态回显Object引用的方法;比如“echo $ scoutChallenge-&gt; variableElement ”,其中variableElement根据switch语句等同于$ badgeShortname?
答案 0 :(得分:1)
答案 1 :(得分:0)
检查:
我认为你可以用
迭代一个对象foreach($object as $attr_name => $attr_value){
echo $attr_value;
}
它仅适用于公共属性。