I would like to find out the correct key that contains the array selected. Right now the code echoes out the next array key of 3 and not 2. This seems very basic. I could fix this by simply subtracting 1, but that seems problematic because the last artist array echoes a position of 0. Can anyone help? (I need to find this key so I can properly set next and previous values.)
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);
}
}
?>
Here is the current output front the above code. I would like the last number "[3]" to report the correct key that contains the data for the id, which is "[2]":
Array ( [0] => Array ( [rank] => 1 [id] => koons_jeff [firstname] => Jeff [lastname] => Koons [bcountry] => US [byear] => 1955 ) [1] => Array ( [rank] => 2 [id] => richter_gerhard [firstname] => Gerhard [lastname] => Richter [bcountry] => DE [byear] => 1932 ) [2] => Array ( [rank] => 5 [id] => doig_peter [firstname] => Peter [lastname] => Doig [bcountry] => UK [byear] => 1959 ) [3] => Array ( [rank] => 7 [id] => marden_brice [firstname] => Brice [lastname] => Marden [bcountry] => US [byear] => 1938 ) )
Current Artist: Peter Doig - UK-1959
3
Instead of
echo key($array);
you want
echo $element;
since $element is the variable assigned in your foreach loop to hold the current key.