i have this script example:
while (count($xml->xpath('*[@id="' . $id . '"]/@id')) > 0)
{
$id = 'example_' . ++$x;
}
But if i check this with 1.000 Childrens in the element, i must wait more than a hour for an response.
How i could quicker check if a id exists?
Thank's in Advance for your Tip!
Thanks @michi:
I modified the example and this is the final answer:
$ids = $xml->xpath('*[@id="' . $id . '"]/@id');
if(count($ids) > 0)
{
$ids = $xml->xpath('*[starts-with(@id, "example_")]/@id');
$id = max(array_map(
function($a)
{
list(, $id) = explode('_', $a);
return intval($id);
}, $ids)) + 1;
$id = 'example_' . $id;
}
=}
get a unique id by grabbing the highest id and add 1 to it.
As you didn't provide an XML, I assume the following for my example:
<elements>
<element id="example_1" />
<element id="example_5" />
<element id="example_27" />
</elements>
This is the code (PHP >= 5.3 for inline function):
$xml = simplexml_load_string($x); // assume XML in $x
$ids = $xml->xpath("//element/@id");
$newid = max(array_map(
function($a) {
list(, $id) = explode("_", $a);
return intval($id); }
, $ids)) + 1;
$newid = "example_$newid";
echo $newid;
Output:
example_28
See it working: http://codepad.viper-7.com/SFvf7v
Comments:
1. the xpath
expression in line 2 builds an array $ids
of all ids in the XML
2. we need to separate the example
from the number at the _
and change the number to int
in order to perform max()
, this is done with array_map()
calling an inline function
3. within this function, we use list()
to grab that number part of the string seperated with explode()
and return it as int