LeeTee
LeeTee

Reputation: 6601

XPATH select random number of nodes AND have multiple conditions

I need to select a random number of product details from XML and have multiple conditions.

The below selects 8 products, but they are not random - how to make this random?

$randomProducts = $prod_xml->xpath("/products/product[position()< 9]");

The below makes a selection on multiple conditions.

$featuredProducts = $prod_xml->xpath('/products/product[featured =1 and hidden !=1]');

How do I combine the two to get random featured products that are not set to hidden?

Upvotes: 3

Views: 1939

Answers (1)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243479

Depending on whether you want first to get all non-hidden and featured products an then select 8 of them, or get 8 products and then select all of them that are featured and non-hidden, you will have two different XPath expressions:

/products/product[featured =1 and hidden !=1][position() < 9]

and correspondingly:

/products/product[position() < 9][featured =1 and hidden !=1]

Now, the "random" part ...

Neither XPath 1.0 nor XPath 2.0 (or even the W3C working drafts for XPath 3.0 and its standard functions) have a function that returns a pseudo-random sequence of integers (or of anything).

Therefore, you have to form this sequence of eight pseudorandoms and generate an XPath expression as this:

/products/product[featured =1 and hidden !=1]
           [contains('|3|5|12|19|4|23|11|7|', concat('|',position(),'|)) ]

Upvotes: 2

Related Questions