我想找出包含所选数组的正确密钥。现在,代码回显了3的下一个数组键,而不是2.这看起来非常基本。我可以通过简单地减去1来解决这个问题,但这似乎有问题,因为最后一个艺术家阵列回应了0的位置。任何人都可以帮忙吗? (我需要找到这个键,以便我可以正确设置下一个和以前的值。)
sample_entries.xml
<?xml version="1.0"?>
<entries>
<entry>
<rank>1</rank>
<id>koons_jeff</id>
<firstname>Jeff</firstname>
<lastname>Koons</lastname>
<bcountry>US</bcountry>
<byear>1955</byear>
</entry>
<entry>
<rank>2</rank>
<id>richter_gerhard</id>
<firstname>Gerhard</firstname>
<lastname>Richter</lastname>
<bcountry>DE</bcountry>
<byear>1932</byear>
</entry>
<entry>
<rank>5</rank>
<id>doig_peter</id>
<firstname>Peter</firstname>
<lastname>Doig</lastname>
<bcountry>UK</bcountry>
<byear>1959</byear>
</entry>
<entry>
<rank>7</rank>
<id>marden_brice</id>
<firstname>Brice</firstname>
<lastname>Marden</lastname>
<bcountry>US</bcountry>
<byear>1938</byear>
</entry>
</entries>
的index.php
<?php
$xml = simplexml_load_file('sample_entries.xml');
$path = $xml->xpath('entry');
//strip simple xml tags.
$array = json_decode( json_encode($path) , 1);
print_r($array);
// cannot change the above XML structure.
echo '<br><br>';
// set page's unique identifier.
$artist = 'doig_peter';
foreach($array as $element => $inner_array) {
if($artist == $inner_array[id]) {
$current_artist = $inner_array;
extract($current_artist);
echo '<b>Current Artist: </b>'.$firstname.' '.$lastname.' - '.$bcountry.'-'.$byear.'<br><br>';
echo key($array);
}
}
?>
这是当前输出前面的代码。我希望最后一个数字“[3]”报告包含id数据的正确密钥,即“[2]”:
数组([0] =&gt;数组([rank] =&gt; 1 [id] =&gt; koons_jeff [firstname] =&gt; 杰夫[姓氏] =&gt;昆斯[bcountry] =&gt;美国[byear] =&gt; 1955)[1] =&gt; 数组([rank] =&gt; 2 [id] =&gt; richter_gerhard [firstname] =&gt; Gerhard [lastname] =&gt;里希特[bcountry] =&gt; DE [byear] =&gt; 1932)[2] =&gt;排列 ([rank] =&gt; 5 [id] =&gt; doig_peter [firstname] =&gt; Peter [lastname] =&gt; Doig [bcountry] =&gt;英国[byear] =&gt; 1959)[3] =&gt;数组([rank] =&gt; 7 [id] =&gt; marden_brice [firstname] =&gt;布里斯[lastname] =&gt;马登 [bcountry] =&gt;美国[byear] =&gt; 1938))
现任艺术家:Peter Doig - UK-1959
3
答案 0 :(得分:2)
而不是
echo key($array);
你想要
echo $element;
因为$ element是在foreach循环中分配的变量,用于保存当前密钥。