我有一个名为$ child的数组,其中至少包含单词。我想遍历数组并将每个单词保存到一个单独的变量中。目前,我尝试了:
for($i = 0; $i < $child->count();$i++)
{
$var1 = (string) $child[$i]->xpath;
$var2 = (string) $child[$i+1]->xpath;
$var3 = (string) $child[$i+2]->xpath;
}
这给出了一个错误,说我正在尝试获取非对象的属性。如果数组中包含更多单词,这种情况也不是很通用。
任何建议将不胜感激。
抱歉,我犯了一个错误,它不是一个单词数组。基本上,我有一个名为$ operation的SimpleXMLElement对象。SimpleXMLElement对象([@attributes] =>数组([type] =>和)[child] =>数组([0] => SimpleXMLElement对象([xpath] => noNotification [assert] =>存在)[1] = > SimpleXMLElement对象([xpath] =>序列[assert] =>不存在)[2] => SimpleXMLElement对象([xpath] => dataType / enumRef [@name ='OperState'] [assert] =>存在))) )
我希望从中提取noNotification,sequence和dataType / enumRef [@name ='OperState']并将它们保存在单独的变量中。但是,我不能直接征求他们的意见,因为如果以后再添加其他元素,则必须动态完成。
首先<
,您的代码中缺少一个小字符。应该是这样的;
for($i = 0; $i < $child->count(); $i++) {
$var1 = (string) $child[$i]->xpath;
$var2 = (string) $child[$i+1]->xpath;
$var3 = (string) $child[$i+2]->xpath;
}
现在回到代码
您将遇到此代码的问题,因为您没有检查是否$child[$i+1]
实际设置。$i
可以达到的最大长度,$child
并且仍会尝试获取下2个元素。因此,您最终会遇到此错误trying to get a property of a non-object
如果您将采用这种方法,那么至少应该这样做。
for($i = 0; $i < $child->count(); $i++) {
$var1 = (string) $child[$i]->xpath;
if (isset($child[$i+1]->xpath)) $var2 = (string) $child[$i+1]->xpath;
if (isset($child[$i+2]->xpath)) $var3 = (string) $child[$i+2]->xpath;
}
为了向您提供更多更好的答案,我们需要了解的结构$child
。
一种或另一种以这种方式循环是非常不好的做法。考虑一下;
$child = array("test1","test2","test3","test4","test5","test6");
for($i = 0; $i < count($child); $i++){
echo $child[$i]."<br />";
if (isset($child[$i+1])) echo $child[$i+1]."<br />";
if (isset($child[$i+2])) echo $child[$i+2]."<br />";
}
您最终将得到重复。因为循环本身正在遍历下一个元素,所以在循环内您还将继续遍历下2个元素。
编辑(查看结构后)
尝试这个;
$words = array();
for($i = 0; $i < count($operation->child); $i++) {
if (isset($operation->child[$i]->xpath)) {
$words[$i] = (string) $operation->child[$i]->xpath;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句