Ответ две петли
сначала вы ищите в xpath старый идентификатор, сохраняете его в массиве
и затем повторите цикл, чтобы заменить сохраненные результаты новым идентификатором
$reorder = array(9 => "8", 8 => "5", 7 => "4", 6 => "3", 5 => "0", 4 => "1", 3 => "9", 2 => "7", 1 => "2", 0 => "6");
$objDOM = new SimpleXMLElement(
'<pictures>
<picture id="9">id was 9, should be 8 now</picture>
<picture id="8">id was 8, should be 5 now</picture>
<picture id="7">id was 7, should be 4 now</picture>
<picture id="6">id was 6, should be 3 now</picture>
<picture id="5">id was 5, should be 0 now</picture>
<picture id="4">id was 4, should be 1 now</picture>
<picture id="3">id was 3, should be 9 now</picture>
<picture id="2">id was 2, should be 7 now</picture>
<picture id="1">id was 1, should be 2 now</picture>
<picture id="0">id was 0, should be 6 now</picture>
</pictures>');
$oldPicIds = array();
foreach ($reorder as $old => $new) {
$oldPicIds[$old] = $objDOM->xpath('picture[@id="' . $old . '"]');
}
foreach ($reorder as $old => $new) {
$oldPicIds[$old][0]['id'] = $new;
}
echo $objDOM->asXML();
Выход:
<?xml version="1.0"?>
<pictures>
<picture id="8">id was 9, should be 8 now</picture>
<picture id="5">id was 8, should be 5 now</picture>
<picture id="4">id was 7, should be 4 now</picture>
<picture id="3">id was 6, should be 3 now</picture>
<picture id="0">id was 5, should be 0 now</picture>
<picture id="1">id was 4, should be 1 now</picture>
<picture id="9">id was 3, should be 9 now</picture>
<picture id="7">id was 2, should be 7 now</picture>
<picture id="2">id was 1, should be 2 now</picture>
<picture id="6">id was 0, should be 6 now</picture>
</pictures>
чтобы сохранить массив, вы можете использовать array_pop
, чтобы получить последнее вхождение picture @ id = xy.
какой должен быть разыскиваемым (см. комментарии к недостаткам)
$reorder = array(9 => "8", 8 => "5", 7 => "4", 6 => "3", 5 => "0", 4 => "1", 3 => "9", 2 => "7", 1 => "2", 0 => "6");
$objDOM = new SimpleXMLElement(
'<pictures>...</pictures>');
foreach ($reorder as $old => $new) {
$picture = $objDOM->xpath('picture[@id="' . $old . '"]');
$picture = array_pop($picture);
$picture['id'] = $new;
}
echo $objDOM->asXML();